AFAIK sizeof doesn't evaluate its operands it C++.
E.g.
int x = 0;
sizeof(x += 1); // value of x is not changed
But what does this mean?
int arr[5];
sizeof(arr+0); // here array is converted to pointer
Why does the arithmetic on array is applied here?
(§ 5.3.3/4) The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the operand of sizeof.
The sizeof() operator is calculated at compile time. The expressions are NOT evaluated. It is the type of the expression that is calculated (at compile time) and then used by sizeof().
So in your first one:
sizeof( x += 1);
The type of x is int. The result of the += operator is still int. So the sizeof() is still the size of int.
In this:
sizeof(arr+0);
Here arr is an array and would have returned the size of the array (if used by itself). But the operator + causes the array to decay into a pointer. The result of the + operator on an array and an integer is a pointer. So here the sizeof() operator will return the sizeof a pointer.
(§ 5.3.3/4) The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are not applied to the operand of sizeof.
This means that:
std::cout << sizeof(arr);
// would print sizeof(int)* 5 (because there is no conversion)
// if sizeof() had behaved like a normal function there
// would have been a conversion but as you pointed out that
// does not apply.
But here:
std::cout << sizeof(arr + 5);
// prints the sizeof(int*) because the result of the expression
// is a pointer type (int*)
This is why
int x[0];
int const xSize = sizeof(x)/sizeof(x[0]);
// This works correctly even though x[0] is technically
// not valid if used in a real expression (but is valid here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With