+ 1
How does increament work?(see description and attached code)
in this code value of d should 14 but is showing 13 https://code.sololearn.com/c0VfRtXRntI1/?ref=app
8 Answers
+ 1
Should it really ? : )
Every increment is prefixed so At the step c=++b, b is incremented to 12 and c=b so 12.
Then d=++c so c is incremented to 13 and d=c so 13.
Then you put the sum in e, so d=13 still. You never have incremented d.
+ 1
This is interesting : p
The result you expect is :
b=(++a);
b+=(++a);
b+=(++a);
Well have you tried to get the result of (++a)+(++a) ? And b=(++a)+(++a)+(++a)+(++a); ?
What can you conclude about the difference in having two operations and three operations ? The precedence of the prefix ++ versus the addition ? The sequence of the operators ?
To go further :
Then consider what happens if you do b=(++a)+(++a); b=b+(++a);
And what if you do b=(++a)+(++a)+(a++); ?
And what about b=(a++)+(++a)+(++a); ?
What if you try to put parenthesis around the first 2 then last 2 additions ?
Using many prefix/postfix expressions in a long sequence of operations can be very, very tricky. Have you tried seeing what you get when you use multiply or divide ?
+ 1
i tried doing with only two ++a and it gives the result as expected. So what i understand is(i maybe wrong) that when we add the third increment the compiler calculates the sum of first two increment terms after incrementing twice and then again increments and adds. i will be trying the rest now
+ 1
To check that, try with four additions.
Then switch back to 3 additions and put parenthesis around the last 2 additions.
It has to do with precedence and associativity of the operators , here is a link on the subject :
https://en.cppreference.com/w/cpp/language/operator_precedence
I have to confess I do not entirely master the subtilities of operation sequences in C, so if you find some unexpected behavior, I would be interested in trying to understand, and if I can't, hopefully someone will be able to answer your questions
+ 1
One last test : with int a=10,c=10,b; try
b=(++a)+(++a)+(++c);
versus
b=(++c)+(++a)+(++a);
It should give you a definite answer about the sequence of operations with your three additions
0
https://code.sololearn.com/cJII7d8grkca/?ref=app
what about in this code? shouldn't the answer be 11+12+13=36?
0
ok. with 4 increments it first increments twice and add then increments third time and add and then again increments fourth time and add. Logically it should have incremented 4 times the value of a and then added because presedence of increment is more than addition, right?
and with three increments with parenthesis on last two it gives the expected result of 39(13+13+13)
0
okay did this and in first case gives 35 and second gives 34 that means two increments are always added and then the remaining increments are carried out.