Hi, I don't know if I good understand that:
a = 3
b = ++a + (a-- * ++a)
1. first a-- from parentheses: b = 3 + (2 * 3)
2. second ++a from parentheses: b = 3 [3-1(postfix a--)+1(prefix ++a)] + (3 [2+1(prefix ++a)] * 3 [3-1(postfix a--)+1(prefix ++a)])
3. third ++a outside parentheses: b = 4 [3+1(prefix ++a)] + (4 [3+1(prefix ++a)] * 4 [3+1(prefix ++a)])
4. b = 4 + (4 * 4)
5. b = 4 + 16
6. b = 20
If that it's true why b = ++a + ++a + (a-- * ++a) give me 34 instead 35 ?
Thanks a lot for yours answers.
Hi, I don't know if I good understand
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
9 August 2022, 20:49solution
With the ++ and -- the difference is that when pre fixes (such as ++a) the value is changed and then plugged into the equation. When it is post fixed (as in a--) the value is plugged into the equation and then changed. This has the highest operator precedence and is done from left to right. So, using a = 3 in all these examples:
1) a-- * ++a
first you would consider the left most unary which is a-- which means you plug 3 into the equation at that spot and then decrement a to 2. Next move right to the ++a and increment a to 3 and then plug it into the equation. The equation becomes 3 * 3 and when run your answer will be 9
2) ++a * a--
the left most unary is ++a which means increment a to 4 then plug that in. Next is a-- so you plug in the value of a of 4 then decrement a. The equation is 4 * 4 and equates to 16
3) ++a + ++a + (a-- * ++a)
The left most unary increases a to 4 then uses that value. The next increases a to 5 then uses that value. The next is a post fixed so the value 5 is used and then a is decremented to 4. The last increases a to 5 and uses that value. The equation becomes 4 + 5 + (5 * 5) which equates to 34
4)++a + a-- + a++ + a-- * ++a
following the above explanation this becomes: 4 + 4 + 3 + 4 * 4 which equates to 27
+2
michal9696
10 August 2022, 18:20
I checked myself and this is my result:
c = 5
++c + ++c + (c-- * c--) + --c
1. ++c
6 + 6 + (6 * 6) + 6
2. ++c
6 + 7 + (7 * 7) + 7
3. c--
6 + 7 + (7 * 6) + 6
4. c--
6 + 7 + (7 * 6) + 5
5. --c
6 + 7 + (7 * 6) + 4
c = 9
c-- + --c + (++c * ++c) + c--
1. c--
9 + 8 + (8 * 8) + 8
2. --c
9 + 7 + (7 * 7) + 7
3. ++c
9 + 7 + (8 * 8) + 8
4. ++c
9 + 7 + (8 * 9) + 9
5. c--
9 + 7 + (8 * 9) + 9
c = 13
c++ + c++ + (--c * --c) + --c
1. c++
13 + 14 + (14 * 14) + 14
2. c++
13 + 14 + (15 * 15) + 15
3. --c
13 + 14 + (14 * 14) + 14
4. --c
13 + 14 + (14 * 13) + 13
5. --c
13 + 14 + (14 * 13) + 12
0
Guadalupe Gagnon
10 August 2022, 18:30
That is all correct!
+2