RK-
RK-

Reputation: 12219

Does sizeof work at compile time?

I ran this sample program.

const int x = 5;
int main(int argc, char** argv)
{
    int x[x];

    int y = sizeof(x) / sizeof(int);

    return 0;
}

The Value of y is 5.

But how is this possible? Because when I debugged, the value of x was 5, so the size of x is 4 and size of int is 4. And value of y should have been different .

What am I missing?

Upvotes: 3

Views: 1355

Answers (4)

David Heffernan
David Heffernan

Reputation: 613541

sizeof(x) refers to the array which has 5 elements of type int. Hence the output.

The code would be a lot easier to understand if you didn't overload the name x.

Technically what you have here is a variable length array, a VLA. This is because C const actually means read-only and has to be evaluated at run time. Hence sizeof, in this case, is evaluated at runtime.

If you had used a literal to size your array instead, i.e. int x[5]; then sizeof would have been evaluated at compile time.

If the code had been compiled as C++ then the const would be a true const, and so available for evaluation at compile time.

Upvotes: 7

Karoly Horvath
Karoly Horvath

Reputation: 96326

Since int x is const, this is a fixed size array. Sizeof is calculated at compilation time.

x has five elements, as the definition clearly shows. It's size is 5 * sizeof(int).

This is GCC, I use printf to print out the value of y:

subl    $48, %esp
movl    $5, 4(%esp)`

Both the allocated space and the value of y is compiled as constants.

Also, from the standard:

If the size is an integer constant expression and the element type has
a known constant size, the array type is not a variable length array type [...]

Upvotes: -2

Eran Zimmerman Gonen
Eran Zimmerman Gonen

Reputation: 4507

You have variable hiding going on here. Your code is roughly equivalent to:

const int x = 5;
int main(int argc, char** argv)
{
    int x2[x];

    int y = sizeof(x2) / sizeof(int);

    return 0;
}

Then it's clearer: sizeof(x)==4, x==5, sizeof(x2)==20.

Upvotes: 4

Arafangion
Arafangion

Reputation: 11950

x is of type int[5]. Therefore, the size is 5*sizeof(int). sizeof is an operator, not a function or a macro.

This is why some people get annoyed when people claim that C arrays are just pointers, but unfortunately you can't pass an array. You can only pass a pointer to it's first element, and you loose this information.

Upvotes: 0

Related Questions