You might be able to do that, but it might also give false results. It depends on the cpu architecture and compiler optimization level.
Originally Posted by Elysia
As an example we can take a variation of anon's code and have it use 2 char variables defined next to each other:
Compiled in debug mode the output is
char a, b;
std::cout << "pointer substraction: " << reinterpret_cast<char*>(&b) - reinterpret_cast<char*>(&a) << std::endl;
std::cout << "sizeof(char): " << sizeof(char) << std::endl;
from both a 32 and 64-bit exe
pointer substraction: 1
However, when compiled in release mode with optimizations enabled the output is
for 32-bit and
pointer substraction: 4
pointer substraction: 8
on an Intel Core2 cpu.
As you can see variables are word-aligned. The only way to make sure your variables are right next to each other without padding is to use an array or the "#pragma pack" directive.