Alternate way of computing size of a type using pointer arithmetic

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

    It is probably implementation defined.

    I can imagine a (hypothetical) system where sizeof(int) is smaller than the default alignment.

    It looks only safe to say that size_of_int >= sizeof(int)

    0 讨论(0)
  • 2021-01-12 05:18

    Why not just:

    size_t size_of_int = sizeof(int);
    
    0 讨论(0)
  • 2021-01-12 05:18

    There was a debate on a similar question.

    See the comments on my answer to that question for some pointers at why this is not only non-portable, but also is undefined behaviour by the standard.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 05:24

    &a+1 will lead to undefined behavior according to the C++ Standard 5.7/5:

    When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. <...> If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

    &a+1 is OK according to 5.7/4:

    For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

    That means that 5.7/5 can be applied without UB. And finally remark 75 from 5.7/6 as @Luther Blissett noted in his answer says that the code in the question is valid.


    In the production code you should use sizeof instead. But the C++ Standard doesn't guarantee that sizeof(int) will result in 4 on every 32-bit platform.

    0 讨论(0)
  • 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++.

    0 讨论(0)
提交回复
热议问题