Is sizeof in C++ evaluated at compilation time or run time?

C++RuntimeSizeofCompile Time

C++ Problem Overview


For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?

sizeof(short int)

C++ Solutions


Solution 1 - C++

sizeof is a compile time operator.

Solution 2 - C++

It depends on the machine executing your program. But the value evaluates at compile time. Thus the compiler (of course) has to know for which machine it's compiling.

Solution 3 - C++

As of C99, sizeof is evaluated at runtime if and only if the operand is a variable-length array, e.g. int a[b], where b is not known at compile time. In this case, sizeof(a) is evaluated at runtime and its result is the size (in bytes) of the entire array, i.e. the size of all elements in the array, combined. To get the number of elements in the array, use sizeof(a) / sizeof(b). From the C99 standard:

> The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

Note that all of this is different from what you'd get if you allocated an array on the heap, e.g. int* a = new int[b]. In that case, sizeof(a) would just give you the size of a pointer to int, i.e. 4 or 8 bytes, regardless of how many elements are in the array.

Solution 4 - C++

sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.

Solution 5 - C++

Anon tried to explain this, but still he nor no one else has stated that your compiler has flags to indicate what processor you are compiling for. This is how sizeof short is known at compile time.

I however feel that any desktop compiler should push out code compatible with desktops. I think the OS provides certain abstractions around this. Even though I hear that windows machines have different architecture from Macintosh machines.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionogzylzView Question on Stackoverflow
Solution 1 - C++Billy ONealView Answer on Stackoverflow
Solution 2 - C++Johannes Schaub - litbView Answer on Stackoverflow
Solution 3 - C++Todor K.View Answer on Stackoverflow
Solution 4 - C++anonView Answer on Stackoverflow
Solution 5 - C++user13947194View Answer on Stackoverflow