what's the mechanism of sizeof() in C/C++? - Stack Overflow
How sizeof works in C/C++
parameters - What arguments does the sizeof operator take in C? - Stack Overflow
Confuso da sizeof integer in C
Videos
You know, there's a reason why there are standard documents (3.8MB PDF); C99, section 6.5.3.4, ยง2:
The
sizeofoperator 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.
In response to ibread's comment, here's an example for the C99 variable length array case:
Copy#include <stdio.h>
size_t sizeof_int_vla(size_t count)
{
int foo[count];
return sizeof foo;
}
int main(void)
{
printf("%u", (unsigned)sizeof_int_vla(3));
}
The size of foo is no longer known at compile-time and has to be determined at run-time. The generated assembly looks quite weird, so don't ask me about implementation details...
sizeof is an operator, not a function.
It's usually evaluated as compile time - the exception being when it's used on C99-style variable length arrays.
Your example is evaluating sizeof(int), which is of course known at compile time, so the code is replaced with a constant and therefore the ++ doesn't exist at run-time to be executed.
Copyint i=0;
cout << sizeof(++i) << endl;
cout << i << endl;
It's also worth noting that since it's an operator, it can be used without the brackets on values:
Copyint myVal;
cout << sizeof myVal << endl;
cout << sizeof(myVal) << endl;
Are equivalent.
sizeof isn't a function, it's a keyword. You could drop the parentheses and it would work just fine. Because it's not a function, it works with any type or object that you give it - it's much more flexible than a function.
sizeof is not a function; it's an operator. It can be used in two ways: as sizeof(typename) and as sizeof expression. The parentheses are required when used with a type name. Parentheses are not needed when the operand is an expression, though for clarity's sake many programmers will parenthesize the expression regardless. Note that unlike most programming languages operators, sizeof expression does not evaluate its argument under normal circumstances, i.e., when its operand is not a C99 variable-length array.