Alternate way of computing size of a type using pointer arithmetic

前端 未结 9 521
广开言路
广开言路 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:27

    It's not 100% portable for the following reasons:

    1. Edit: You'd best use int a[1]; and then a+1 becomes definitively valid.
    2. &a invokes undefined behaviour on objects of register storage class.
    3. In case of alignment restrictions that are larger or equal than the size of int type, size_of_int will not contain the correct answer.

    Disclaimer:

    I am uncertain if the above hold for C++.

提交回复
热议问题