sizeof操作数得到评估? [英] sizeof operands get evaluated?

查看:114
本文介绍了sizeof操作数得到评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK sizeof不评估其操作数C ++。

AFAIK sizeof doesn't evaluate its operands it C++.

例如

int x = 0;
sizeof(x += 1); // value of x is not changed

但这是什么意思?

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节)左值到右值(4.1),数组到指针(4.2)和
函数到指针(4.3)的标准转换不适用于sizeof的
操作数。

(§ 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.


推荐答案

sizeof()运算符是在编译时计算的。表达式进行评估。是表达式的类型(在编译时),然后由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);

x的类型是int。 + =运算符的结果仍为int。因此,sizeof()仍然是整数的大小。

The type of x is int. The result of the += operator is still int. So the sizeof() is still the size of int.

在此:

sizeof(arr+0);

这里arr是一个数组,将返回数组的大小(如果单独使用)。但是运算符+会使数组衰减为指针。数组和整数上的+运算符的结果是指针。因此,这里的sizeof()运算符将返回指针的大小。

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节)左值到右值(4.1),数组对指针(4.2)和函数对指针(4.3)标准转换不适用于sizeof的操作数。

(§ 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.

这意味着:

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.

但在这里:

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

这篇关于sizeof操作数得到评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆