In C, comma operator doesn't produce an lvalue, consequently the array arr
which is an lvalue decays into a pointer type which is a rvalue (in this case). So sizeof(0,arr)
becomes equivalent to sizeof(char*)
, due to lvalue-to-rvalue conversion.
But in C++, comma operator produces an lvalue. There is no lvalue-to-rvalue conversion. So sizeof(0,arr)
remains same, which is equivalent to sizeof(char[100])
.
By the way, sizeof
is not a function, it's an operator. So the following is completely valid C++ (and C, if you imagine printf
instead of cout
):
int a[100], b[200], c[300], d[400];
cout << sizeof(a,b,c,d) << endl;
Demo : http://www.ideone.com/CtEhn
You might think that I've passed 4 operands to sizeof
but that is wrong. sizeof
operates on the result of the comma operators. And its because of the many comma operators you see many operands.
4 operands with 3 comma operators; just like in 1+2+3+4
, there're 3 operators, 4 operands.
The above is equivalent to the following (valid in C++0x):
auto & result = (a,b,c,d); //first all comma operators operate on the operands.
cout << sizeof (result) << endl; //sizeof operates on the result
Demo : http://www.ideone.com/07VNf
So it's the comma operator which makes you feel that there are many arguments. Here comma is an operator, but in function call, comma is NOT an operator, its simply argument separator.
function(a,b,c,d); //here comma acts a separator, not operator.
So sizeof(a,b,c,d)
operates on the type of the result of ,
operators, exactly in the same way, sizeof(1+2+3+4)
operates on the type of the result of +
operators.
Also note that you cannot write sizeof(int, char, short)
, precisely because comma operator cannot operate on types. It operates on value only. I think, sizeof
is the only operator in C and C++, which can operate on types as well. In C++, there is one more operator which can operates on types. Its name is typeid
.
sizeof
with 2 params. It's defined as a unary operator with optional use of()
, which would sort of rule out multiple params. – Gardantsizeof
here is using the comma operator. i.e.sizeof x
wherex
is the expression(0, arr)
. – Lowman