Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 652
xmllmx Avatar asked Nov 08 '25 02:11

xmllmx


1 Answers

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.

like image 165
Jesse Chisholm Avatar answered Nov 10 '25 18:11

Jesse Chisholm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!