...
Also, consider using the sprintf_s() function, defined in ISO/IEC TR 24731-1, instead of snprintf() to provide some additional checks. (See STR07-C. Use the bounds-checking interfaces for string manipulation.)
Noncompliant Code Example (enum)
In this noncompliant code example, initializer expressions for all enumeration constants in the enum attrib_mask are unsigned integers. However, the C Standard says (section 6.4.4.3, paragraph 2 [ISO/IEC 9899:2011]) that enumeration constants have type int. The bitwise OR is applied to signed integers which is implementation-defined.
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum attrib_mask
{
POINT_BIT = 0x02U,
LINE_BIT = 0x04U
};
unsigned int mask = (POINT_BIT | LINE_BIT);
|
Compliant Solution (enum)
One solution is to cast the enumeration constants to an unsigned type to eliminate any possible implementation-defined behavior. The initializer expressions and enumeration constants have type int:
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum attrib_mask
{
POINT_BIT = 2,
LINE_BIT = 4
};
unsigned int mask = ((unsigned int)POINT_BIT | (unsigned int)LINE_BIT); |
Exceptions
INT13-EX1: When used as bit flags, it is acceptable to use preprocessor macros or enumeration constants as arguments to the & and | operators even if the value is not explicitly declared as unsigned.
...