this post was submitted on 05 Apr 2025
161 points (96.0% liked)

Programmer Humor

34976 readers
4 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] SpaceNoodle@lemmy.world 46 points 1 week ago* (last edited 1 week ago) (1 children)

If I'm writing C++, I'm usually optimizing for portability over performance, in which case I would prefer std::endl as it would yield the best results regardless of platform; it also keeps the end-of-line character out of other strings, making code just a little cleaner.

\n is for when I'm done pretending that anything that isn't Unix-like is OK, or I'm counting the cycles of every branch instruction.

[–] barubary@infosec.exchange 32 points 1 week ago (2 children)

std::endl provides zero portability benefits. C++ does have a portable newline abstraction, but it is called \n, not endl.

[–] Albbi@lemmy.ca 49 points 1 week ago

Thank you two for demonstrating the image in the post so well.

[–] SpaceNoodle@lemmy.world 7 points 1 week ago (1 children)

No, there's no guarantee that in every context \n is translated portably.

[–] barubary@infosec.exchange 15 points 1 week ago (2 children)

The same is true of std::endl. std::endl is simply defined as << '\n' << std::flush; nothing more, nothing less. In all cases where endl gives you a "properly translated" newline, so does \n.

[–] SpaceNoodle@lemmy.world 6 points 1 week ago (1 children)

Ahhh, I see. Looks like the magic happens somewhere further down in iostream.

[–] AnyOldName3@lemmy.world 3 points 1 week ago

It's controlled by whether the stream's opened in text mode or binary mode. On Unix, they're the same, but on Windows, text mode has line ending conversion.

[–] zenforyen@feddit.org 2 points 1 week ago

Yeah it's an artificial dichotomy based on a popular misconception of what std::endl is and how \n is interpreted.

Ultimately it does not ask about line endings, but about flushing, which is a completely orthogonal question.