pai said:
hi..
I have a simple doubt about increment operators..
Can any one tell me what is really happening..
Eg:
Your code is incomplete, and horribly difficult to read with that much
indentation (one reason may be using TABs in the original file, which
is almost always a bad idea).
You're missing:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
These are better put on separate lines, or at least horizontally spaced.
Choose from:
int i = 0, ans;
and
int i = 0;
int ans;
( ans = ++i ++i //
This
gives error while compiling )
This is not a legal C comment (nor are C++ style ones, at least for on
compiler).
Of course this is a syntax error. Sequence <expression1> <whitespace>
<expression2> is not legal in C. You have `++i` as both expression 1
and 2. If you expected something different (and I can't see what that
might have been), keep in mind that compiler follows `maximum munch`
rule, i.e. it reads the code sequentially and tries to make sense of
the longest possible legal sequence of characters. In your case these
are both `++i`s, but stringing them together does not make sense.
ans = ++i + +i ;
printf(" %d %d ",ans,i); // it prints 2 1
This is undefined behaviour. The `++i` bit can be executed at any time
during the evaluation of the expression (but before the sequence point
marked with `;` in your case, and after the previous one, which in your
case is the previous `;`). The same holds true for taking the value of
`i` for the second part of your expression (`+` in `+i` is unary plus,
which does exactly the same as +2 does in mathematics, i.e. nothing
much). Your compiler has chosen to first do `++i` then take value of
`i`, and evaluate expression as 2. It might have decided to do it the
other way around, and give you 0.
i=0;
ans = ++i + ++i ;
printf(" %d %d ",ans,i); // it prints 4 2
U.B. here as well, and your compiler chooses to be consistent and first
do both `++i`s, then perform addition, and give you 4 as a result.
i=0;
ans = ++i + ++i + ++i;
Same again here, but now the compiler apparently decides to deal with
the first two `++i`s first, add the results, only then perform the
third `++i`, and add that to the running total.
NB, all these are just my double-guessing what your compiler decided to
do on this particular occasion. Next week it may decide to do something
entirely different. Do not do these things (and do not rely on what
this compiler does when switching to a different one).
printf(" %d %d ",ans,i); // it prints 7 3
It is actually lucky that you get anything out of this program, as you
did not terminate the printf() with '\n' to force flushing of stdout.
You've missed these as well:
return 0;
}
How do 4 and 7 came can any one explain...
As Keith pointed out elsethread reading the C FAQ at
http://www.c-faq.com/ (maybe even the whole thing, not just 3.2 he
suggested) would help you know the answers to such questions (or even
not to try to ask them of the compiler at all) immediately.
Cheers
Vladimir