Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added an _Alignof example

...

Noncompliant Code Example (_Generic)

This compliant noncompliant solution attempts to modify a variable's value as part of the _Generic association list. The user may have expected the value of a to be 2 because the type of the variable is int, but because _Generic does not evaluate its operands, the result is undefined behavior.

...

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);
} 

Noncompliant Code Example (_Alignof)

This noncompliant code example attempts to modify a variable while getting its default alignment value. The user may have expected val to be incremented as part of the _Alignof expression, but because _Alignof does not evaluate its operand, the result is undefined behavior.

Code Block
bgColor#FFcccc
langc
#include <stddef.h>
 
void func(void) {
  int val = 0;
 
  /* ... */
 
  size_t align = _Alignof(++val);
 
  /* ... */
}

Compliant Solution (_Alignof)

 The compliant solution moves the expression out of the _Alignof operator.

Code Block
bgColor#ccccFF
langc
#include <stddef.h>
void func(void) {
  int val = 0;
 
  /* ... */
 
  ++val;
  int align = _Alignof(val);
 
  /* ... */
}

Risk Assessment

If expressions that appear to produce side effects are supplied to an operator that does not evaluate its operands, the results may be different than expected. Depending on how this result is used, it can lead to unintended program behavior.

...