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 | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
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)