Bellala's blog

By Bellala, history, 3 years ago, In English

I was taught not to write things like a=a+++++a.

However I love writing a++ because I believe that it always gets executed after a whole sentence (perhaps, right after a , or ;?)

But today I wrote this and got WA:

if(hh < tt && a[hh+1] == a[hh]-1) c[hh+1] += 2*c[hh++];

wa code: 154812779

rewrote it like this and got AC:

if(hh < tt && a[hh+1] == a[hh]-1) c[hh+1] += 2*c[hh], hh++;

ac code: 154812722

I'm wondering if it's wrong somewhere else or am I misunderstanding the usage of x++?

  • Vote: I like it
  • +13
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it +10 Vote: I do not like it

It's an undefined behavior in C++.

"More than one modifications of the same scalar in an expression without any intermediate sequence point (until C++11) that is unsequenced (since C++11)" is a kind of UB.

Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.

See this for more infomation.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    What is "more than one modifications of the same scalar" here?

    If I just modify c[hh+1] and let hh++, like c[hh+1] += hh++, then hh will definitely be changed after c[hh+1].

    But in c[hh+1] += 2*c[hh++], c[hh+1] may be changed twice, so it is possible that hh++ was done before it. Am I right?

    • »
      »
      »
      3 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      Yeah, I think so. You modified hh and get the reference of c[hh+1], and it is called "more than one modifications".

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      In this code, you know first the computer should calculate c[hh+1]('s address) and hh++, but it is not defind that c[hh+1] or hh++ which is calculated first. Because hh++ will change hh, so which one is calculated first influences the array c.

»
3 years ago, # |
  Vote: I like it +1 Vote: I do not like it

It is undefined behavior in C++. In different computer or use different compiler it may get different output. You can use -Wall to find undefined behavior.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks! I tried it and get "warning: operation on 'hh' may be undefined [-Wsequence-point]".