C++/programming math
Expert: Eddie - 9/18/2005
Questioni am using microsoft visual C++. I am a beginner in programming and has some problem with math in programming.
int i=3, c=10;
printf("x=--c+2 => %d\n",(--c+2));
Output is 9.
printf("x=i--+ ++c =>%d\n",(i++ + ++c);
Output is 13.
I would like to know how these output is calculated out by the computer. Hope u could help me with that. Thanks!
AnswerHello cyberbatt, thank you for the question.
This is interesting. I just went and had this tested on both Linux and Windows, and could not produce the answer of 9 on the first operation. It should be 11, as this is a prefix operation. The --c becomes 9 before any other code is executed, and then 2 is added. Any info you would like to provide on that one would be interesting, as me and coworkers were perplexed on how you could get 9.
For the second statement, the answer 13 is correct. You have this operation: i++ + ++c
Which becomes: 3++ + ++9
Since c was just decremented the statement before. Since the 3++ is a postfix operation, it is not incremented to 4 until after this print statement has executed, and the ++9 statement is prefix so it happens inline so you get this:
3 + 10, which is 13. After this statement executes, the 3 becomes 4, since this was a postfix operation.
If you have any other questions, please feel free to ask.
I hope this information was helpful.
- Eddie