int a=10; int b=(++a)+(++a) b is 24
Another
int a=10; int b=(++a) + (++a) + (--a) + (++a); b is 47
HOW BOTH IS WORKING
# | User | Rating |
---|---|---|
1 | tourist | 3947 |
2 | jiangly | 3734 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3612 |
7 | ecnerwala | 3581 |
8 | Geothermal | 3569 |
8 | cnnfls_csy | 3569 |
10 | ksun48 | 3479 |
# | User | Contrib. |
---|---|---|
1 | awoo | 162 |
2 | maomao90 | 160 |
3 | nor | 156 |
3 | adamant | 156 |
5 | -is-this-fft- | 155 |
5 | atcoder_official | 155 |
7 | maroonrk | 153 |
7 | cry | 153 |
9 | SecondThread | 147 |
10 | Petr | 146 |
int a=10; int b=(++a)+(++a) b is 24
Another
int a=10; int b=(++a) + (++a) + (--a) + (++a); b is 47
HOW BOTH IS WORKING
Name |
---|
Very classic undefined behavior.
It's undefined behavior. Just never use more than one prefix/postfix operator on the same variable within a single expression in C++. Depending on C++ version and your compiler, some such atrocities may be undefined, unspecified, or well-defined behavior, but there is no reason to remember the specifics given that it's harder to both read and reason about.
The rules about order of evaluation for parts of an expression are very complicated and leave room for the compiler to choose. If you really want to know what happens behind the scenes, you can always choose your settings and use something like godbolt to explore the assembly generated. For example, in your first example, the assembly indicates that a is increased twice and then summed with itself. It might give you insight about what exactly the compiler does, but it is not hugely practical knowledge as it may depend on too many factors.
For the curious (at least with the version of C++/gcc I tried), the two examples effectively compile to (simplified):
1)
2)