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

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

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
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится +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.

  • »
    »
    2 года назад, # ^ |
      Проголосовать: нравится 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?

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

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

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

      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.

»
2 года назад, # |
  Проголосовать: нравится +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.

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

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