int i = 0, j = 0;
int *a , *b;
a = &i + 1;
b = &j;
printf(" %p \n ",a);
printf(" %p \n ",b);
if(a==b)
printf(" yo \n");
Output:
0x7ffda8e133a4
0x7ffda8e133a4
a is same as b, still printf does not execute.
ideone link to this code
This works well, when I make a and b as normal variables. (int a, b;)
ISO/IEC 9899:201x
§6.5.6 Equality operators:
- Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
but then again:
- For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
So ... a and b should behave the same as a pointer to an array and i and j happen to be next to each other in memory ... then &i + 1 could point to the beginning of the first "array element" of j (b). Well, that's a big if. I wouldn't rely on that. Maybe in packed structs.
@OmG
The last version of the code works for me! [with initialized
iandj]
gcc 9.1 -O3, 2 x printf() then ret.
sub rsp, 24
mov edi, OFFSET FLAT:.LC0
xor eax, eax
lea rsi, [rsp+12]
mov DWORD PTR [rsp+8], 0
mov DWORD PTR [rsp+12], 0
call printf ; <----------
lea rsi, [rsp+12]
mov edi, OFFSET FLAT:.LC0
xor eax, eax
call printf ; <----------
xor eax, eax
add rsp, 24
ret ; <----------
godbolt Compiler Explorer, gcc 9.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With