EDIT: The original word choice was confusing. The term "symbolic" is much better than the original ("mystical").
In the discussion about my previous C++ question, I have been told that pointers are
- "a simple value type much like an integer"
- not "mystical"
- "The Bit pattern (object representation) contains the value (value representation) (§3.9/4) for trivially copyable types, which a pointer is."
This does not sound right! If nothing is symbolic and a pointer is its representation, then I can do the following. Can I?
#include <stdio.h>
#include <string.h>
int main() {
int a[1] = { 0 }, *pa1 = &a[0] + 1, b = 1, *pb = &b;
if (memcmp (&pa1, &pb, sizeof pa1) == 0) {
printf ("pa1 == pb\n");
*pa1 = 2;
}
else {
printf ("pa1 != pb\n");
pa1 = &a[0]; // ensure well defined behaviour in printf
}
printf ("b = %d *pa1 = %d\n", b, *pa1);
return 0;
}
This is a C and C++ question.
Testing with Compile and Execute C Online with GNU GCC v4.8.3: gcc -O2 -Wall
gives
pa1 == pb
b = 1 *pa1 = 2
Testing with Compile and Execute C++ Online with GNU GCC v4.8.3: g++ -O2 -Wall
pa1 == pb
b = 1 *pa1 = 2
So the modification of b
via (&a)[1]
fails with GCC in C and C++.
Of course, I would like an answer based on standard quotes.
EDIT: To respond to criticism about UB on &a + 1
, now a
is an array of 1 element.
Related: Dereferencing an out of bound pointer that contains the address of an object (array of array)
Additional note: the term "mystical" was first used, I think, by Tony Delroy here. I was wrong to borrow it.
a
to an array. – Indict&a + 1
is undefined, and the compiler is free to assume that doing it does not modifyb
and instead inlineb
's value. – Argufyb
is not an element of the array, so the behaviour is undefined. – Selflovea
to array of 1 int, the pointer it is valid. – Indictint
s,float
s, and everything else. Using the value of an uninitialisedint
object is also undefined, regardless of the bit pattern it stores. – Argufy