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?
sizeof(x)refers to the array which has5elements of typeint. 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
constactually means read-only and has to be evaluated at run time. Hencesizeof, in this case, is evaluated at runtime.If you had used a literal to size your array instead, i.e.
int x[5];thensizeofwould 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.