ga******@gmail.com (Ganesh) writes:
da***********@yahoo.com wrote in message
news:<a3**************************@posting.google. com>... #include<stdio.h>
int main(void)
{
unsigned int a=20,b=50, c = sizeof b+a;
printf("%d\n",c);
return 0;
}
out put:
24
"sizeof" is a compile-time operator... That means it is evaluated when
your C code is compiled. But the "+" operator (on non-constants) is a
run-time operator... That means it is evaluated when your program
actually runs. So...
Since the compiler cannot evaluate your "+" operator... It behaves
smart and takes only the first variable as the <operand> for the
"sizeof" operator. And replaces the "sizeof <operand>" instance with
it's value (which is 4 in your case). And...
The "+" operator operates on this value (4) and the remaining operand
at runtime. Em...
I think I'm clear...
Yes, you're clear, but unfortunately you're wrong.
The distinction between compile-time and run-time operators has
absolutely nothing to do with the issue. It's just a matter of the
way the expression is parsed. Informally, the "sizeof" unary operator
has higher precedence than the "+" operator. The same thing applies
to the other unary operators, such as unary "-" and unary "*".
(I say "informally" because the standard doesn't really talk about
operator precedence; all this stuff is actually determined by the
grammar.)
For that matter, the references to b and a could be replaced with the
integer constants 50 and 20 (*), causing everything to be evaluted at
compilation time, and in C99 the sizeof operator applied to a VLA is
evaluated at run time. Again, this has no effect on how the
expressions are parsed.
The expression
sizeof b + a
is equivalent to
sizeof(b) + a
The spacing in
sizeof b+a
is misleading, but is ignored by the compiler, just as the spacing in
x * y+z
is ignored ("x*y + z" would be clearer).
If you want the sizeof to apply to the expression "b + a", you can do
so by adding parentheses:
sizeof(b+a)
(*) Replacing the reference to b and a with the integer constants 50
and 20 does change the type of the expression from unsigned int to
int, but that's not particularly significant.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.