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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
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)