Alternate way of computing size of a type using pointer arithmetic

前端 未结 9 455
广开言路
广开言路 2021-01-12 04:53

Is the following code 100% portable?

int a=10;
size_t size_of_int = (char *)(&a+1)-(char*)(&a); // No problem here?

std::cout<

        
9条回答
  •  悲哀的现实
    2021-01-12 05:20

    No. This code won't work as you expect on every plattform. At least in theory, there might be a plattform with e.g. 24 bit integers (=3 bytes) but 32 bit alignment. Such alignments are not untypical for (older or simpler) plattforms. Then, your code would return 4, but sizeof( int ) would return 3.

    But I am not aware of a real hardware that behaves that way. In practice, your code will work on most or all plattforms.

提交回复
热议问题