3

我的编译器是最新的 VC++ 2013 预览版。

int main()
{
    __declspec(align(4))           int n1 = 0; // OK.
    __declspec(align(sizeof(int))) int n2 = 0; // error C2059: syntax error : 'sizeof'
}

为什么 sizeof 表达式不是像 2、4、8 等这样的编译时常量?

4

2 回答 2

4

Rather than asking: Why is the sizeof expression not a compile-time constant like 2, 4, 8, etc.?

(because, actually, it is a compile time constant just like those examples. (: barring Variable Length Arrays from the newer C standards, for which it must be a run time expression :))

It would be better to ask: Why is it that align(...) does not accept a compile time constant like a sizeof expression?

Microsoft defined __declspec(align(#)) to only accept a small set of values: See: https://msdn.microsoft.com/en-us/library/83ythb65.aspx

"# is the alignment value. Valid entries are integer powers of two from 1 to 8192 (bytes), such as 2, 4, 8, 16, 32, or 64."

So even with simple constants, not just any value is allowed. __declspec(align(7)) would not be allowed, as it isn't a power of 2. Even simple expressions like __declspec(align(4+4)) are not allowed.

于 2015-07-27T22:40:46.467 回答
0

在 C 标准中

sizeof运算符不得应用于具有函数类型或不完整类型的表达式、此类类型的括号名称或指定位字段成员的表达式。_Alignof 运算符不应应用于函数类型或不完整类型。

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

于 2013-10-07T15:22:49.040 回答