I have an array that I would like to initialize
char arr[sizeof(int)];
Would this expression evaluate to a compile time constant or result in a function call?
I have an array that I would like to initialize
char arr[sizeof(int)];
Would this expression evaluate to a compile time constant or result in a function call?
char arr[sizeof(int)];
As far as the language is concerned, it is fine, though the array is only declared (and defined), it is NOT initialized if it is a local variable. If it is declared at namespace level, then it is statically zero-initialized.
Note that sizeof(int)
is a constant expression of size_t
type; its value is known at the compile time.
This is an initialization:
char arr[sizeof(int)] = { 'A', 'B', '0', 'F' };
This of course assumes that sizeof(int)
is (at least) 4, or it will fail to compile.
And to answer the actual (new) question:
sizeof()
is a compile time operator. In C++ [according to the standard, some compilers do allow C style variable length arrays], it will not result in anything other than a compile time constant. In C, with variable length arrays, it can become a simple calculation (number of elements * size of each element - where number of elements is the variable part).
There is no initialization here. There's nothing wrong with declaring or defining an array with sizeof(int)
elements, except that it might look a little odd to readers of the code. But if that's what you need, that's what you should write.
It really depends on how you intend to use the array.
sizeof(int)
may vary with different implementations so you just need to be careful how you access the elements in the array. Don't go assuming that an element that is accessible on your machine is accessible on another, unless it's within the minimum sizes specified in the C++ standard.
sizeof
is evaluated at compile time, the only time sizeof would would be run time evaluated would be in the case of variable length arrays in C99
code or in gcc
or other c++ compilers that support VLA
as an extension. So this code is valid:
char arr[sizeof(int)];
Although if it is local variable it won't be initialized.