在C++中,我完全意識到指針減法僅在數組內有效,下面的代碼是未定義的行爲。我知道嘗試推理未定義的行爲是毫無意義的,但我相信在詢問以下問題時有價值。2個指針,0字節差異但不等於
#include <cstddef>
#include <iostream>
#include <iomanip>
int main()
{
long a = 1;
long b = 1;
std::cout << (char*)(&b) - (char*)(&a) << '\n'; //prints 8, ok we're 8 bytes apart
char* aPlus8 = (char*)&a + 8; //bump up 8 bytes
char* bPtr = (char*)&b;
std::cout << "diff in bytes = " << (bPtr - aPlus8) << '\n'; //prints 0. All good, looks like we're there
std::cout << "but are they the same? = " << (bPtr == aPlus8) << '\n'; //but are we ?
}
最後一行bPtr == aPlus8
返回false,雖然字節差異是0.是否有可能的解釋? (除「因爲它是未定義的行爲」)
這是與g++ -std=c++14 -O3 -Wall -pedantic
編譯。如果我改變優化級別,那麼預期的結果也會改變。
C或C++?決定一個。您可以嘗試使用較少的優化級別編譯來檢查結果是否相同。 –