Reputation: 1056
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.
Upvotes: 0
Views: 2416
Reputation: 279255
p
didn't get incremented because sizeof
does not evaluate its operand, it just uses the type of the expression.
sizeof
is an operator taking a single expression as its operand, not a parenthesized argument list. So, in sizeof(a,b)
, the single operand is (a,b)
. The comma in sizeof(a,b)
therefore is the comma operator -- unlike the comma in printf("%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. Hence sizeof(a,b)
is equivalent to sizeof(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 sizeof
is 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:
#include <stdio.h>
int main() {
int a = 10;
int b[a]; // VLA
const char *p = "Hello";
printf("%d\n", sizeof(++p, b));
printf("%d\n", sizeof b);
printf("%c", *p);
}
prints (on my machine):
4
40
H
because in the first sizeof
, even though there's a VLA on the RHS of the comma operator, the type of the operand of sizeof
is int*
, not a VLA, and so (++p, b)
is not evaluated. In the second sizeof
, the type of the operand is a VLA, which is evaluated, and its size is 10*sizeof(int)
.
Upvotes: 10
Reputation: 137322
sizeof
operator is a compiler function (e.g. calculated to constant at compile time).
sizeof(a,b)
is like sizeof(b)
)Upvotes: 1