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)
. 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).