C_o_d_e__'s blog

By C_o_d_e__, history, 10 months ago, In English
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

  • Vote: I like it
  • -5
  • Vote: I do not like it

»
10 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

[unwanted explanation]

  • »
    »
    10 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Then how int a=10; int b=(++a)+(++a); according to you b will 23 but answer is 24

»
10 months ago, # |
  Vote: I like it 0 Vote: I do not like it

»
10 months ago, # |
  Vote: I like it +15 Vote: I do not like it

Very classic undefined behavior.

»
10 months ago, # |
  Vote: I like it +37 Vote: I do not like it

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)

a += 1
a += 1
b = a + a

2)

a += 1
a += 1
b = a + a
a -= 1
b += a
a += 1
b += a