• Aatube@kbin.melroy.orgOP
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    8 months ago

    I forgot the alt text 🤦 here’s the markdown (source):

    Trimming whitespaces before line splicing

    As of C++20, what’s the output of the below piece of code (Godbolt)?

    int main() {
    int i = 1
    // \ 
    + 42
    ;
    return i;
    }
    

    Without having seen how the code is formatted I would have said that it’s 1 + 42, so 43. And actually, that’s the real output. On MSVC. Not on other compilers, such as GCC and Clang.

    These latter ones return 1. The reason is that they trim the trailing whitespaces before handling \ splicing. The new-line character following \ is a whitespace, it’s deleted, therefore + 42 ends up on the same line as // \ and it becomes part of the comment.

    Just for the record, both implementation strategies are valid.

    P2223R2 change this situation and set the GCC/Clang implementation strategy into stone standard. This might be a breaking one for code that is only compiled with MSVC, but it shouldn’t happen on a big scale.

    We might remember Matt Godbolt saying earlier in one of his talks that one of the superpowers of C++ is backward compatibility and here the change potentially breaks code. At the same time, it’s worth noting that implementation-defined behaviour would break here and not standardized behaviour.

    The reason behind going in this direction is that many IDEs, code formatters and other tools already discard trailing whitespaces as the Google style guide and most of its derivations already forbid them.

    I’ve changed the Godbolt link and code because the original didn’t have the trailing whitespace, lol.