Considering :
double data;
double array[10];
std::vector<int> vec(4, 100);
MyClass myclass;
Is there a difference between :
sizeof(double);
sizeof(double[10]);
sizeof(std::vector<int>);
sizeof(MyClass);
and
sizeof(data);
sizeof(array);
sizeof(vec);
sizeof(myclass);
Are the two syntaxes different or strictly equivalent ? Are all of them evaluated at compile-time ? If not, which one is evaluated at run-time ?
The latter is defined in terms of the former. Given an expression, it returns the size of the type of the expression. So
sizeof(vec)
translates tosizeof(std::vector<int>)
.Both are evaluated at compile-time; the only run-time
sizeof
is in C, not C++, with variable-length arrays. The operand tosizeof
is unevaluated, so there isn't any real possibly the expression itself could generate code anyway.I prefer to use expressions over types, because chances are stating the type is redundant in some fashion.
The only differences are in syntax and convenience.
Syntactically, you're allowed to leave out the parentheses in one case, but not the other:
As far as convenience goes, consider something like:
If, for example, you sometime end up changing
a
from afloat
to a double, you'd also need to changesizeof(float)
tosizeof(double)
to match. If you usesizeof(a)
throughout, when you changea
from afloat
to adouble
, all your uses ofsizeof
will automatically change too, without any editing. The latter is more often a problem in C than C++, such as when calling malloc:vs.
In the first case, changing the first
float
todouble
will produce code that compiles, but has a buffer overrun. In the second case, changing the (only)float
todouble
works fine.Whenever you use
sizeof(<whatever>)
, it is always evaluated at compile time. It is the datatype of the parameter thatsizeof
is concerned with.However, you can pass values, and even expressions as parameter. But the sizeof function will only consider the dataype of the passed parameter.
You can also pass expressions as
sizeof(x = x+1);
. Sayx
was int. In this case thissizeof
will return4
(as on my machine) and the value of x will remain unchanged. This is becausesizeof
is always evaluated at compile time.The two set of syntax you provide, will return the same result, but you cannot say they are equivalent. But yes, latter is defined in terms of former.