i wrote the following program and it's output is 14.
How is the output 14...should'nt it be 13..??Code:#include <stdio.h> main() { int i=5; printf("%d",++i + ++i); }
can someone explain..??
i wrote the following program and it's output is 14.
How is the output 14...should'nt it be 13..??Code:#include <stdio.h> main() { int i=5; printf("%d",++i + ++i); }
can someone explain..??
Read the various entries in this C FAQ on expressions.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
went through the FAQ but still cannot determine the logic in my program..
can you please post a little explanation..
In other words, you don't understand the FAQ that I linked to. Okay, here's a simplified version: what you are trying to do results in undefined behaviour, which is a Bad Thing. It results in undefined behaviour because you are trying to modify i twice between consecutive sequence points (in this case, within the same expression). Hence, there is no logic to explain: what you are doing is simply wrong. The compiler is perfectly fine in causing the output to be 14. It could have made the output 13, 12, or "hello world", and it would still be fine, because of the undefined behaviour.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
ok..thanks for the explanation..
i read the FAQ which said absolutely the same thing..
"The behaviour cannot be determined..."
But it is the first time i came across this kind of question.
so i was little perplexed..
Any Way Thank you
@laserlight..
The order of evaluation of (++i + ++i) is not defined. In your case what happened is that both pre-increment operations were performed before doing the addition. Effectively what you I got the same result of 14 with 3 different versions of microsoft compilers, but with another compiler the result might be 13. In the case where the result is 14, the effect was the the same as (not really sure if this is defined, but it may be easier to understand):
Code:printf("%d\n", i + (i = i + 2));
Last edited by rcgldr; 05-02-2013 at 01:44 AM.
That is not accurate. The issue here is not about the order of evaluation. The issue here is that the behaviour is undefined.Originally Posted by rcgldr
Here's a trick question: given the program that narendrav posted in post #1, which of these options labelled A to D is not a possible valid output of the program?
A) 12
B) 13
C) 14
D) 15
The C99 version rule is:Originally Posted by rcgldr
Hence the behaviour is undefined because you modify i, yet you also read i for a purpose other than to determine the value to be stored.Originally Posted by C99 Clause 6.5 Paragraph 2
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)