How to use increment and decrement operators in different compilers?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to use increment and decrement operators in different compilers??

for example int a=5; priintf("%d,%d",a,a++);in one compiler output is 5,5.in another compiler output is 6,5.

10th Feb 2019, 2:37 PM
sampath sarinivas
sampath sarinivas - avatar
9 Answers
+ 3
If you use a, a++ and/or ++a within the same statement, you can't predict in what order they will be executed. That's why you should never use expressions like a = a++ + ++a. It's up to the compiler how to evaluate a statement like this. You might get the expected result on your platform and a totally different result on another.
10th Feb 2019, 5:27 PM
Anna
Anna - avatar
+ 3
Tortello, you should read Anna's post again carefully. This is about using and changing the same variable *more than once* in the same statement!
10th Feb 2019, 7:38 PM
HonFu
HonFu - avatar
+ 2
HonFu you right!! Anna my bad!
10th Feb 2019, 7:42 PM
Pedro Tortello
Pedro Tortello - avatar
+ 2
At the same time, I am also wondering. The typical recommendation is 'don't CHANGE the var twice in a statement'. OP changes it only once, and uses it once without changing it. So I also assumed he should be able to rely on the result.
10th Feb 2019, 7:43 PM
HonFu
HonFu - avatar
+ 2
I don't know how printf works exactly, but I guess you just can't predict in what order the string is built. Maybe the a++ part is evaluated before the a part, then the result will be 6,5. Maybe it's the other way round and the result will be 5,5.
10th Feb 2019, 8:41 PM
Anna
Anna - avatar
+ 1
Make sure you wrote exactly the same code on both compilers. If you changed a++ to ++a then you will end up with this kind of "strange" behavior on output. This is because ++a adds up before the variable is returned and a++ returns the variable before the add.
10th Feb 2019, 2:44 PM
Pedro Tortello
Pedro Tortello - avatar
+ 1
There's this thing called 'undefined behaviour' with the sideeffect operators; often it is recommended to change the same value only once per statement. But, well, you seem to be doing this, and still... I hope we'll hear an explanation. I usually try to keep expressions with ++ and -- as conventional and simple as possible in order to be safe, but am I safe? Let's take another compiler and see. ^^ I agree with Python's decision not to implement sideeffect assignments at all.
10th Feb 2019, 3:01 PM
HonFu
HonFu - avatar
0
I have wrote same code on both compilers but it's showing different outputs on both compilers
10th Feb 2019, 2:45 PM
sampath sarinivas
sampath sarinivas - avatar
0
Anna that is not what this lesson teaches: https://www.sololearn.com/learn/CSharp/2590/ It says the use of prefix or postfix operators have different results.
10th Feb 2019, 7:18 PM
Pedro Tortello
Pedro Tortello - avatar