Originally Posted by
Elysia
intervade: Assuming these variables are declared next to each other, you should be able to simply subtract the address from the one with the highest address with the one with the lowest. This should be simple subtraction, only that for each digit, there are 16 combinations instead of 10.
You might be able to do that, but it might also give false results. It depends on the cpu architecture and compiler optimization level.
As an example we can take a variation of anon's code and have it use 2 char variables defined next to each other:
Code:
#include <iostream>
void main()
{
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;
}
Compiled in debug mode the output is
pointer substraction: 1
sizeof(char): 1
from both a 32 and 64-bit exe
However, when compiled in release mode with optimizations enabled the output is
pointer substraction: 4
sizeof(char): 1
for 32-bit and
pointer substraction: 8
sizeof(char): 1
for 64-bit
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.