Is the following code 100% portable?
int a=10;
size_t size_of_int = (char *)(&a+1)-(char*)(&a); // No problem here?
std::cout<<size_of_int;// or printf("%zu",size_of_int);
P.S: The question is only for learning purpose. So please don’t give answers like Use sizeof() etc
From ANSI-ISO-IEC 14882-2003, p.87 (c++03):
This seems to suggest that the pointer difference equals to the object size.
If we remove the UB’ness from incrementing a pointer to a scalar a and turn a into an array:
Then this looks OK. The clauses about alignment requirements are consistent with the footnote, if alignment requirements are always divisible by the size of the object.
UPDATE: Interesting. As most of you probably know, GCC allows to specify an explicit alignment to types as an extension. But I can’t break OP’s “sizeof” method with it because GCC refuses to compile it:
The message is
error: alignment of array elements is greater than element size.