smilinginpain's blog

By smilinginpain, history, 3 years ago, In English

In the recent CF round 752, my solution gave WA in C++20 while it got AC in C++17.

Can someone explain the reason?

Links-

WA (C++20) https://codeforces.me/contest/1604/submission/133650638

AC (C++17) https://codeforces.me/contest/1604/submission/133701300

Thanks!

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

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

You have undefined behaviour when you acess a[n]

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

    Yeah, but why C++17 works for undefined behaviour also? I just copy-pasted the same code in C++17, and it got accepted..any reasons for that? Why it passes in C++17 and fail in C++20?

    The final solution which got accepted had the loop till n-1 and in C++17.

    https://codeforces.me/contest/1604/submission/133651687

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

      You got lucky that it passes. Undefined behaviour would lead to stranger things.

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

        Not that lucky. It resulted in a -8 submission. Still, it was worth it.

        Thanks:)

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

      Undefined behavior is undefined

      By the C++ standard, if your computer literally blew up when you accessed an array out of bounds, that would still be allowed. Don't ever rely on it working, because otherwise you will get problems like this.

      Yes, I know it hurts to get WA because of UB. I for one got 4 WA in a recent Atcoder contest because I forgot to initialize my arrays large enough. But that means you should make sure that it won't happen again in another contest, right?

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

        Thanks, yes, I tried my code with n-1 in C++20, it got accepted. I guess the C++17 compiler is not that precise, or it somehow passed that failing test case, or it was my luck that it got accepted with UB in C++17. I got to learn a new thing today and will keep this in mind next time. Thanks, mate :)

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

    i tried to find out the pattern in c++ someday last year , similar with your problem here ,, and i found that in some standards(or it's related to the IDE u used) c++ will give more space than you ask(a little space after the end of your definition will not be used what ever happen in ur program) , but i still don't know exactly why and how it work .. so ,, it seem not just luck mayb..