0
c = a++ + ++a + ++a +a; if a = 10 ...c=?, a =? final value
So ,we have to solve postfix first or prefix first?
11 Answers
+ 6
pooja sharma this will result in an undefined behaviour and you cannot predict the answer. This is caused due to the sequence point issue where a single variable is modified more than once in a single expression.
You might get a result but this is compiler dependent and will result in different values in different compilers.
https://code.sololearn.com/c4pkgpqi6277/?ref=app
A similar question.
https://www.sololearn.com/Discuss/2111410/?ref=app
+ 6
Arb Rahim Badsa
It works well in Java also.
https://code.sololearn.com/cdLY8L6VjsqS/?ref=app
It is just that the order of evaluation is well defined in these languages when compared to C or C++.
+ 4
a = 10;
c = a++ + ++a + ++a + a;
First 'a++' is 10. Because it's a postfix increment. Hence it will first assigned to c and then will increased by 1. Next '++a' is 12. It is a prefix increment, therefore a will be first increased by 1 and then assigned to c. The second '++a' is 13 and however, for the same reason a is now 13. So, c is :
c = 10 + 12 + 13 + 13; // 48
Therefore, the output is 48.
+ 2
Answer is 48 watch this video u will understood the concepts
https://youtu.be/XKPPLdKZIYs
+ 2
According to https://en.cppreference.com/w/cpp/language/operator_precedence the order of execution of the operations is:
1. suffix increment has the highest precedence and it is running left-to-right
2. prefix increment has lower precedence and it is running right-to-left
3. addition has lower precedence and it is running left-to-right
4. it is finally executed direct assignment operator
In our case we have two prefix increment(i.e. "++a" operation is performed twice from left to right)
a = 10; c = a++ + ++a + ++a + a;
c = 10 + ++a + ++a + a;
c = 10 + ++a + 12 + a;
c = 10 + 13 + 12 + a;
c = 10 + 13 + 12 + 13;
c = 23 + 12 + 13;
c = 35 + 13;
c = 48;
Finally c is 48, a is 13.
+ 1
It is not so well defined in C or C++ and they can again differ based on the compiler they are executed on.
You can go through this tutorial.
https://www.learncpp.com/cpp-tutorial/increment-decrement-operators-and-side-effects/
In general if there are two operators with same precedence in a single expression than you must follow the associative property and should evaluate the expression from left to right.
0
Avinesh That was a nice info :))
It, however, works well in javascript :
https://code.sololearn.com/WzAyHXLDYn2s/?ref=app
0
c/c++ have sequence point issues but, in other are strongly typed languages are well defined their way of evoluation of expressions and order executions.. So we we get well defined output when compared to c/c++.
0
But still I have a doubt that if multiple ++ or -- are occurring then we to solve prefix and than only postfix
0
a clear case of sequence point.
doing more than two increments in the same expression is always an undefined behaviour.
0
48 bro.