...
In this noncompliant code example, the expression a++
is not evaluated and the side effects in the expression are not executed.
Code Block | ||||
---|---|---|---|---|
| ||||
int a = 14; int b = sizeof(a++); |
...
In this compliant solution, the variable a
is incremented.
Code Block | ||||
---|---|---|---|---|
| ||||
int a = 14; int b = sizeof(a); a++; |
...
In the following noncompliant code example, the expression ++n
in the initialization expression of a
must be evaluated since its value affects the size of the variable length array operand of the sizeof
operator. However, since the expression ++n % 1
evaluates to 0
, regardless of the value of n
, its value does not affect the result of the sizeof
operator, and, thus, it is unspecified whether n
is incremented or not.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t n) { size_t a = sizeof(int [++n]); /* n must be incremented */ size_t b = sizeof(int [++n % 1 + 1]); /* n need not be incremented */ /* ... */ } |
...
The compliant solution below avoids changing the value of the variable n
used in the sizeof
expression and instead increments it safely outside of it.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(size_t n) { size_t a = sizeof(int [n + 1]); ++n; size_t b = sizeof(int [n % 1 + 1]); ++n; /* ... */ } |
...