Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 in the initialization expressino of b, the expression ++n % 1 evaluates to 0, regardless of . This means that the value of n, its value does  does not affect the result of the sizeof operator. Consequently, it is unspecified whether or not n is  will be incremented when initializing b.

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]);
  
  /* ... */
}

...

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

Code Block
bgColor#ccccFF
langc
#include <stddef.h>
 
void f(size_t n) {
  size_t a = sizeof(int[n + 1]);
  ++n;

  size_t b = sizeof(int[n % 1 + 1]);
  ++n;
  /* ... */
}

...