Here is a C code snippet
char *p="Hello World";
int a;
char b;
printf("%d\n",sizeof(p++));
printf("%c\n",*p);
printf("%d",sizeof(a,b));
printf("%d",sizeof(b,a));
Here is the output
4
H
1
4
Can anybody explain why p didn’t get incremented and what is the use of comma operator here. I read that it has something to do with VLAs.
pdidn’t get incremented becausesizeofdoes not evaluate its operand, it just uses the type of the expression.sizeofis an operator taking a single expression as its operand, not a parenthesized argument list. So, insizeof(a,b), the single operand is(a,b). The comma insizeof(a,b)therefore is the comma operator — unlike the comma inprintf("%c\n", *p), which is an argument separator and not the comma operator.When evaluated, the comma operator first evaluates its left-hand side, then evaluates the right-hand side. The result of the operator is the result of the right-hand side. So, although
(a,b)isn’t evaluated, the type of the expression is the type of the right-hand side. Hencesizeof(a,b)is equivalent tosizeof(b). Really there’s no “use” of the comma operator here, at least no useful use. It’s pointless other than to test your ability to read it.It has nothing to do with VLAs (variable-length arrays).
What does have to do with VLAs is that when
sizeofis applied to a VLA, it is defined to evaluate the expression (6.5.3.4/2 in C99). The size of a VLA is of course not known at compile-time.But, when used on the RHS of a comma operator, the name of a VLA decays to a pointer just like any other array does. This is 6.3.2.1/3: there are three cases where an array does not decay, and “the operand of sizeof” is one of them but “the RHS of a comma operator” is not. So:
prints (on my machine):
because in the first
sizeof, even though there’s a VLA on the RHS of the comma operator, the type of the operand ofsizeofisint*, not a VLA, and so(++p, b)is not evaluated. In the secondsizeof, the type of the operand is a VLA, which is evaluated, and its size is10*sizeof(int).