+ 1

Can anyone explain how the output is 150? i Cant understand the operator precedence!!

main(){ int i=3,j; j= ++i * ++i * ++i; printf("%d",j); } https://code.sololearn.com/cgn1g0m3v7w1/?ref=app https://code.sololearn.com/cql2b8wAg539/?ref=app whats the difference between these two codes one outputs 150 and another 120!

26th Apr 2018, 6:07 AM
Uday
Uday - avatar
3 ответов
+ 1
When you use ++i you telling the system to increment the value of i by 1 before the operation, in this case, the system will increment i twice(i=5) then it will multiply i*i now the system will start the next operation, 25*++i. The system again will increase i by one so of course, now you have the operation 25*6 giving 150. The reason your loop code output is different is because i is only incremented once per operation. So as the loop runs j*= ++i is j=1*4 is j = 4 j*= ++i is j=4*5 is j = 20 j*= ++i is j=20*6 is j = 120
26th Apr 2018, 8:21 AM
ODLNT
ODLNT - avatar
+ 3
The behavior of such expressions (++i * ++i * ++i) is undefined in C/C++. In your case, I think its 5*5*6 = 150.
26th Apr 2018, 6:23 AM
Ali Zhussupov
Ali Zhussupov - avatar
+ 1
Each factor in ++i * ++i * ++i can be either 4 or 5 or 6 (because i increments 3 times). Then the drunk C compiler throws a dice to decide which of them what. However, this thing works fine in C# and you can predict the result.
26th Apr 2018, 6:47 AM
Ali Zhussupov
Ali Zhussupov - avatar