ogzylz
ogzylz

Reputation: 1395

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

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

sizeof(short int)

Upvotes: 88

Views: 41024

Answers (5)

user13947194
user13947194

Reputation: 420

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.

Upvotes: 0

Todor K.
Todor K.

Reputation: 651

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.

Upvotes: 15

anon
anon

Reputation:

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.

Upvotes: 9

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507403

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.

Upvotes: 18

Billy ONeal
Billy ONeal

Reputation: 106609

sizeof is a compile time operator.

Upvotes: 95

Related Questions