C++ – Why sizeof is Called a Compile-Time Operator

c

Originally, this is a part of another question.

Why is sizeof called a compile-time operator? Isn't it actually a run-time operator? And if it is indeed a compile-time operator, how does it help in producing portable code which runs the same in different computers ? Please explain in detail.

Best Answer

sizeof() gives you the size of the data type, not the size of a particular instance of that type in memory.

For example, if you had a string data object that allocated a variable size character array at runtime, sizeof() could not be used to determine the size of that character array. It would only give you the size of the pointer.

The size of a data type is always known at compile time.