开发者

sizeof operands get evaluated?

开发者 https://www.devze.com 2023-04-13 05:05 出处:网络
AFAIK sizeof doesn\'t evaluate its operands it C++. E.g. int x = 0; sizeof(x += 1); // value of x is not changed

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 开发者_如何学Python(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*)

As a side note:

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).


It isn’t. In an arithmetic expression, array names decay into pointers. That says nothing about performing the calculation itself. The type of + is deducible from the types of its operands, in this case pointer and integer, yielding the same result as sizeof(int*).


I don't know much about this, but if as you say, sizeof doesn't evaluate its operand then it must just rely on the type of the expression it's used on. So I would guess that arr on its own has a different type to arr+0, and that's why it was used.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号