Main Content

Use of plain char type for numeric value

Plain char variable in arithmetic operation without explicit signedness

Description

This defect occurs when char variables without explicit signedness are used in these ways:

  • To store non-char constants.

  • In an arithmetic operation when the char is:

    • A negative value.

    • The result of a sign changing overflow.

  • As a buffer offset.

char variables without a signed or unsigned qualifier can be signed or unsigned depending on your compiler.

Risk

Operations on a plain char can result in unexpected numerical values. If the char is used as an offset, the char can cause buffer overflow or underflow.

Fix

When initializing a char variable, to avoid implementation-defined confusion, explicitly state whether the char is signed or unsigned.

Extend Checker

A default Bug Finder analysis might not raise this defect when the input values are unknown and only a subset of inputs cause an issue. To check for defects caused by specific system input values, run a stricter Bug Finder analysis. See Extend Bug Finder Checkers to Find Defects from Specific System Input Values.

Examples

expand all

#include <stdio.h>

void badplaincharuse(void)
{
    char c = 200;
    int i = 1000;
    (void)printf("i/c = %d\n", i/c);
}

In this example, the char variable c can be signed or unsigned depending on your compiler. Assuming 8-bit, two's complement character types, the result is either i/c = 5 (unsigned char) or i/c = -17 (signed char). The correct result is unknown without knowing the signedness of char.

Correction — Add signed Qualifier

One possible correction is to add a signed qualifier to char. This clarification makes the operation defined.

#include <stdio.h>

void badplaincharuse(void)
{
    signed char c = -56;
    int i = 1000;
    (void)printf("i/c = %d\n", i/c);
}

Result Information

Group: Numerical
Language: C | C++
Default: Off
Command-Line Syntax: BAD_PLAIN_CHAR_USE
Impact: Medium

Version History

Introduced in R2016b