Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can sizeof() be used to define an array length?

I know that in C, arrays are not supposed to be dynamically sized.

With that in mind, would the following code be allowed? (Trying to declare an array of chars the same length as a double.)

char bytes[sizeof(double)];

My guess is that sizeof operates on its argument during program execution and so this wouldn't be allowed, but I'm not sure.

Also, would there be a difference if this were C++ instead of C?

like image 605
llakais Avatar asked Nov 23 '11 08:11

llakais


1 Answers

The sizeof expression is evaluated at compile time (by the compiler not the preprocessor) so the expression is legal.

There's an exception to this rule in C99 where dynamic arrays are allowed. In that case sizeof is, depending on context, evaluated at runtime (http://en.wikipedia.org/wiki/Sizeof). It doesn't change the legality of the expression in the question.

like image 60
sashang Avatar answered Sep 25 '22 06:09

sashang