C++ 中的 sizeof 是在编译时还是运行时计算的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2615203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:05:53  来源:igfitidea点击:

Is sizeof in C++ evaluated at compilation time or run time?

c++runtimesizeofcompile-time

提问by ogzylz

For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?

例如,此代码片段的结果取决于哪台机器:编译器机器或机器可执行文件工作?

sizeof(short int)

回答by Billy ONeal

sizeofis a compile time operator.

sizeof是一个编译时操作符。

回答by Johannes Schaub - litb

It depends on the machine executing your program. But the value evaluates at compile time. Thus the compiler (of course) has to know for which machine it's compiling.

这取决于执行程序的机器。但该值在编译时计算。因此编译器(当然)必须知道它正在为哪台机器编译。

回答by Todor K.

As of C99, sizeof is evaluated at runtime if and only if the operand is a variable-length array, e.g. int a[b], where b is not known at compile time. In this case, sizeof(a) is evaluated at runtime and its result is the size (in bytes) of the entire array, i.e. the size of all elements in the array, combined. To get the number of elements in the array, use sizeof(a) / sizeof(b). From the C99 standard:

从 C99 开始,当且仅当操作数是可变长度数组时,才会在运行时计算 sizeof,例如 int a[b],其中 b 在编译时未知。在这种情况下,sizeof(a) 在运行时被评估,其结果是整个数组的大小(以字节为单位),即数组中所有元素的大小,组合。要获取数组中的元素数,请使用sizeof(a) / sizeof(b)。来自 C99 标准:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

sizeof 运算符产生其操作数的大小(以字节为单位),它可以是表达式或类型的括号名称。大小由操作数的类型决定。结果是一个整数。如果操作数的类型是变长数组类型,则对操作数求值;否则,不计算操作数并且结果是整数常量。

Note that all of this is different from what you'd get if you allocated an array on the heap, e.g. int* a = new int[b]. In that case, sizeof(a) would just give you the size of a pointer to int, i.e. 4 or 8 bytes, regardless of how many elements are in the array.

请注意,所有这些都与在堆上分配数组时得到的不同,例如int* a = new int[b]. 在这种情况下,sizeof(a) 只会为您提供指向 int 的指针的大小,即 4 或 8 个字节,而不管数组中有多少元素。

回答by Todor K.

sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.

sizeof 在编译时计算,但如果将可执行文件移动到编译时间和运行时值不同的机器上,则可执行文件将无效。