+ 5
Please help me! Read Description. 🙏🏻🙏🏻🥺🥺
#include<stdio.h> int main() { int a = 2, b = 3; a = a + b - (b = a); printf("%d %d", a, b); return 0; } Output: 3 2 Why output is 3 2?? According to priority, bracket should be solved first. Why (b = a) is not evaluated first? As it has brackets around it, increasing it's priority. So why it is not like this? >> a = a + b - (2) >> a = 2 + 2 - 2 (Cuz b is 2 now) >> a = 2. Why it is not like this? What's the meaning of bracket then? Priority should be given to brackets first? Please explain.
13 Respuestas
+ 5
Angelo , A. S. , Jayakrishna🇮🇳 , Mr.Imperfect , Théophile and Ярослав Вернигора(Yaroslav Vernigora)
Thank you so much all of you. Now, I am clear about it. So grateful to have SoloLearn app! ✨😊
+ 4
Hello First of all, I recommend you to learn "operator priority" This link will help you.
https://en.cppreference.com/w/cpp/language/operator_precedence
And here are the examples.
https://www.programiz.com/cpp-programming/operators-precedence-associativity
+ 3
You are confusing execution with evaluation
a = a + b - (b=a)
First evaluates the components (in an undefined order):
a= 2 + 3 - (b=2)
Than it executes
(With parenthesis you change the order of execution)
+ 3
As Angelo tried to say, we don't care about the result : it is UNDEFINED BEHAVIOR, meaning that nobody can predict the result.
As a general rule, we don't modify the value of a variable inside an expression, since it leads to undefined behaviors.
+ 2
Maybe it's better with an example:
a= 2 * 3 + b
Evaluation:
a=2*3+3
Execution:
a=6+3
a=9
a=2*(3+b)
Evaluation:
a=2*(3+3)
Execution:
a=2*6
a=12
+ 2
Hi! maybe it will help you to better understand the visualization of the code step by step. here on this site. true, I have never used it yet, and so I am not sure that it will work in your case, but still try it:
http://pythontutor.com
+ 2
Evaluation expressions is left to right for equaliry operator.. here a = a + b -(b=a)
Here, before assigning b=a , first b is already gets replaced by its previous value 3. After that b value changed to a in stack so it is evaluated as a = 2+3-(2) = 3
So now a =3, b =2
but order of execution of expressions is compiler dependent in c/c++.
+ 1
No, although there are some rules (that change between versions of c/c++), the order of evaluation is undefined
+ 1
a=a+b-(b=a)
=> a=2+3-(b=2)
=> a=5-2
=> a=3
Than
print 3 2
+ 1
According to first of all solve bracket then solve next
a=a+b-(b=a)
a=2+3-2
a=3
Then print
3 2
Because you are change value before print.
0
Angelo But why output is coming 3 2?
0
A. S. If 'b' becomes 2 then why first 'b' in the expression is taken as 3? Why not a=2+2-2 ??
- 1
C plus plus class I am new student