Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: used VLA acronym

...

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,

...

VLA)

In 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.

Code Block
bgColor#FFcccc
langc
#include <stddef.h>
 
void f(size_t n) {
  /* n must be incremented */ 
  size_t a = sizeof(int[++n]);
 
  /* n need not be incremented */
  size_t b = sizeof(int[++n % 1 + 1]);
  
  /* ... */
}

Anchor
cs_vla
cs_vla

Compliant Solution (sizeof,

...

VLA)

This compliant solution avoids changing the value of the variable n used in the sizeof expression and instead increments it safely outside of it:

...