This is doing my head in! I was doing some experiments with the stack during function calls, and I came across this little anomaly. Compiler is GCC 4.9.2, and -O1, -O2, or -O3 optimization flags. The problem is not present when optimizations are disabled (-O0). The result is the same whether compiling under C++98, C++11 or C++14.
In the example below, I assume that the CDECL calling convention is used for the call to result(), so args should get pushed on the stack from right to left.
#include <iostream>
void result(int a, int b) {
int* pA = &a;
int* pB = &b;
// pA should be equal to pB + sizeof(int) bytes, why does this report "false"
// when optimizations are on?
std::cout << (pA == pB + 1 ? "true" : "false") << '\n';
// this appears to be true if we dump the pointer addresses.
std::cout << pA << ", " << pB + 1 << '\n';
// and still holds water when getting values through indirection.
std::cout << "a: " << *(pB + 1) << " b: " << *pB << '\n';
}
int main(int argc, char** argv)
{
result(10, 20);
return 0;
}
Sample output with optimizations enabled:
false // why?
0x704eca3c088c, 0x704eca3c088c // clearly they're equal
a: 10 b: 20 // and point to the correct arguments on the stack
Sample output with optimizations disabled:
true
0x7e5bd5f34fdc, 0x7e5bd5f34fdc
a: 10 b: 20
What about the compiler optimizations would cause a stack pointer comparison to fail, when their equality can be compared visually and found to be true, optimizations or no?
Edit: I believe this question differs from the suggested duplicate (Is it unspecified behavior to compare pointers to different arrays for equality?) as stacks are traditionally implemented as a contiguous array (obviously with exceptions -- case in point), and the proposed duplicate gives an example of two distinct arrays.