I wrote the code about sizeof
operator. If I write something like:
#include <stdio.h>
int main() {
char a[20];
printf("%zu\n", sizeof(a));
return 0;
}
Output:
20 // Ok, it's fine
But, If I use the comma operator like this:
#include <stdio.h>
int main() {
char a[20];
char b;
printf("%zu\n", sizeof(b, a));
return 0;
}
Output:
8 // Why the output 8?
So, I have a questions:
8
in second example?comma
operator into sizeof()
operator?The comma operator has no special meaning to sizeof . sizeof(b, a) examines the complete expression (b, a) , works out the resultant type, and computes the size of that type without actually evaluating (b , a) .
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
1) Comma as an operator: The comma operator (represented by the token, ) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.
The comma operator has no special meaning to sizeof
.
sizeof(b, a)
examines the complete expression (b, a)
, works out the resultant type, and computes the size of that type without actually evaluating (b , a)
. As noted by chqrlie in comments, the ()
are part of the expression for which the size (of the result) is evaluated.
In this case, b
is a char
and a
is an array. If the expression b, a
was to be evaluated, b
would be evaluated first, the result discarded. Then a
would converted to a pointer (char *
) with value equal to &a[0]
which would be the result of the expression (b, a)
.
Since the result of b, a
is of type char *
, sizeof(b,a)
is equal to sizeof (char *)
. That is an implementation defined value but, for your compiler, has a value of 8
(which probably means the code is being built as a 64-bit application).
In most cases, arrays decay into pointers. So the type of b,a
with a comma operator is a char*
(not a char[20]
anymore). And pointers are 8 bytes on your machine.
BTW, I think that using sizeof
on some comma operator is really confusing to the reader. I recommend using sizeof
on simple expressions or on types.
(and I just discovered this is one of the tricky differences between C and C++; see this explanation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With