Блог пользователя Bellala

Автор Bellala, история, 5 лет назад, По-английски

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++?

  • Проголосовать: нравится
  • +13
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
 
Проголосовать: нравится +10 Проголосовать: не нравится

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.

  • »
    »
    5 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    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?

»
5 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

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.