Reputation: 42215
My compiler is the latest VC++ 2013 preview.
int main()
{
__declspec(align(4)) int n1 = 0; // OK.
__declspec(align(sizeof(int))) int n2 = 0; // error C2059: syntax error : 'sizeof'
}
Why is the sizeof expression not a compile-time constant like 2, 4, 8, etc.?
Upvotes: 3
Views: 2310
Reputation: 4005
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.
Upvotes: 4
Reputation:
In the C Standard
The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member. The _Alignof operator shall not be applied to a function type or an incomplete type.
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.
Upvotes: 0