...
Code Block |
---|
|
#include <stdio.h>
void f(void) {
if (sizeof(int) == sizeof(float)) {
float f = 0.0f;
int *ip = (int *)&f;
printf("float is %f\n", f);
(*ip)++; /* Diagnostic required */
printf("float is %f\n", f);
}
}
|
...
Code Block |
---|
|
#include <stdio.h>
void f(void) {
if (sizeof(int) == sizeof(float)) {
float f = 0.0f;
float *fp = &f;
printf("float is %f\n", f);
(*fp)++;
printf("float is %f\n", f);
}
}
|
...
Code Block |
---|
|
#include <stdio.h>
void func(void) {
short a[2];
a[0]=0x1111;
a[1]=0x1111;
*(int *)a = 0x22222222; /* Violation of aliasing rules */
printf("%x %x\n", a[0], a[1]);
/* ... */
} |
When translating this code, an implementation can assume that no access through an integer pointer can change the array a
, consisting of shorts. Consequently, printf()
may be called with the original values of a[0]
and a[1]
. The actual behavior is implementation-defined and can change with optimization level.
...
Code Block |
---|
|
#include <stdio.h>
void func(void) {
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]);
/* ... */
} |
This code example now reliably outputs "2222 2222."
...