Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits; reviewed

...

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. When   In most cases, the operand is not evaluated.  A possible exception is when the type of the operand is a variable length array type (VLA) the expression is evaluated; otherwise, the operand is not evaluated. When part of the operand of the sizeof operator is a VLA type and when changing the value of the VLA's size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated. See unspecified behavior 22 in Annex J of the C Standard.

...

Code Block
bgColor#FFcccc
langc
void func(void) {
  int a = 14;
  int b = sizeof(a++);

}

Consequently, the value of a after b has been initialized is 14.

...

Code Block
bgColor#ccccff
langc
void func(void) {
  int a = 14;
  int b = sizeof(a);
  ++a;

}

Anchor
ncce_vla
ncce_vla

Noncompliant Code Example (sizeof, Variable Length Array)

In the following this noncompliant code example, the expression ++n in the initialization expression of a must be evaluated because its value affects the size of the VLA operand of the sizeof operator. However, because the expression ++n % 1 evaluates to 0, regardless of the value of n, its value does not affect the result of the sizeof operator. Consequently, it is unspecified whether or not n is incremented.

...

This compliant solution uses the result of the _Generic operator to perform the side-effectassign the correct value to a.

Code Block
bgColor#ccccFF
langc
#define S(val) _Generic(val, int : 2, \
                             short : 3, \
                             default : 1)
void func(void) {
  int a = 0;
  a = S(a);
} 

...