Search code examples
c++platformendl

Difference between std::endl and \n (Regarding Platform Awareness)


Before you declare this question as a duplicate of this or that, please consider that I've submitted a problem to the online judge with \n and got WA, and then with std::endl and got AC. So, I need a very specific answer to the point of platform awareness: Is \n really platform aware, and does the runtime really write the correct line ending according to the platform as the answers to the other questions claim? If so, could you please tell me how this happened??

If the answer can be supported by a citation from the standard regarding the platform awareness issue, I'd be really thankful. I've read all the other questions' answers (even the closed ones), so please don't repeat the "flushes the buffer" thing.


Solution

  • From C++11, §27.7.3.8 -

    namespace std
    {
        template <class charT, class traits>
            basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
    }
    

    Effects:Calls os.put(os.widen(’\n’)), then os.flush().

    Returns:os.

    So, from the standard it's clear that endl flushes the output stream buffer, while \n doesn't. Generally you will want to use endl for printing a new line, but you should also keep in mind that every time you do that the output buffer will get flushed too.

    About the platform awareness

    From the standard it's obvious that both does the exact same thing - printing a new line in the exact same way. So, if one is platform independent, then the other should also be the same. Since I know for sure endl is platform independent, same should be the case for \n.