Versions Compared

Key

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

Modifying a variable through a pointer of an incompatible type can lead to unpredictable results. This is often caused by a violation of aliasing rules. C99C11, Section 6.5, paragraph 7 [ISO/IEC 9899:1999] specifies those circumstances in which an object may or may not be aliased.

...

Code Block
bgColor#FFCCCC
langc

union a_union {
  int i;
  double d;
};

int f() {
  a_union t;
  int *ip;
  t.d = 3.0;
  ip = &t.i;
  return *ip;
}

...

Code Block
bgColor#FFCCCC
langc

union a_union {
  int i;
  double d;
};

int f() {
  double d = 3.0;
  return ((union a_union *) &d)->i;
}

...

Code Block
bgColor#ccccff
langc

union a_union {
  int i;
  double d;
};
          
int f() {
  a_union t;
  t.d = 3.0;
  return t.i;
} 

...

Code Block
bgColor#FFCCCC
langc

short a[2];

a[0]=0x1111;
a[1]=0x1111;

*(int *)a = 0x22222222;  /* violation of aliasing rules */

printf("%x %x\n", a[0], a[1]);

...

Code Block
bgColor#ccccff
langc

union {
  short a[2];
  int i;
} u;

u.a[0]=0x1111;
u.a[1]=0x1111;

u.i = 0x22222222;

printf("%x %x\n", u.a[0], u.a[1]);

...