Problem with (a * a++) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problem with (a * a++)

Hello guys, I have a problem in Visual Studio! The output of the following command in Visual Studio is 4 and in DEV-C++ is 6! What's wrong with this? Which one is right!? https://code.sololearn.com/c9ozKZbjD3nR/?ref=app

23rd Aug 2019, 7:59 AM
Fardin Karimi
Fardin Karimi - avatar
3 Answers
+ 5
The expression you mentioned leads to undefined behaviour, meaning the result depends on the compiler being used to evaluate it. There is no 'right' solution in this case, which is why such statements should be avoided. More on undefined behaviour here: https://www.viva64.com/en/w/v567/
23rd Aug 2019, 8:11 AM
Shadow
Shadow - avatar
+ 5
Both IDE was right, in their own vision of how that expression was supposed to be evaluated. IIRC this problem has something to do with something called 'sequence point' (might wanna search the net for that, for C++ in particular). The difference of output was due to difference in how those IDE work out the expression evaluation, so it is compiler implementation dependent. In this case VS evaluates 2 * 2 (yields 4), but Dev-C++ evaluates it as 2 * 3 (yields 6). All this happens because a variable value is accessed and modified in the same execution point, best to avoid such practices, because when it happens the output is not finite, different compiler gives out different result. Hth, cmiiw
23rd Aug 2019, 8:16 AM
Ipang
+ 1
Thanks a lot
23rd Aug 2019, 8:14 AM
Fardin Karimi
Fardin Karimi - avatar