October 22, 2024
Chicago 12, Melborne City, USA
C++

Strict Aliasing and Unions in C


Consider the following C program (which is based on an example from this article):

#include <stdio.h>

short g(int *p, short *q) {
  short z = *q; *p = 10; return z;
}

int main(void) {
  union int_or_short { int x; short y; } u = { .y = 3 };
  int *p = &u.x;
  short *q = &u.y;
  short r = g(p, q);
  printf("%hd %d\n", r, u.x);
}

Does this program exhibit undefined behavior? Please explain by referring to specific passages in the C17 Standard.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video