I am interested in the definedness (undefinedness, implementation-definedness) of casts from pointers to integers and various related operations. Mostly I am interested in C11, but answers for other standard versions (or even C++) are welcome.
For the purposes of this question, assume that the C implementation provides intptr_t.
Consider the following functions:
#include <assert.h>
#include <stdint.h>
int x;
int y;
int z[2];
void f1(void) {
int *p = &x;
intptr_t i = p;
}
void f2(void) {
int *p = &x;
intptr_t i1 = p;
intptr_t i2 = p;
assert(i1 == i2);
}
void f3(void) {
int *p1 = &x;
int *p2 = &y;
intptr_t i1 = p1;
intptr_t i2 = p2;
assert(i1 != i2);
}
void f4(void) {
int *p1 = &x;
intptr_t i1 = p1;
int *p2 = i1;
intptr_t i2 = p2;
assert(i1 == i2);
}
void f5(void) {
int *p1 = &z[0];
int *p2 = &z[1];
intptr_t i1 = p1;
intptr_t i2 = p2;
assert(i1 < i2);
}
- Which of the functions invoke undefined (implementation-defined) behavior?
- Does anything change if using
void*instead ofint*? How about any other data type as the target of the pointer? - Does anything change if I use explicit casts from from
int*tointptr_tand back? (Asking since GCC warns about the casts.) - Which
asserts are guaranteed never to trigger?