News for hackers. Stuff that matters.
Re:Learn Modern C++ by jenadine on Tuesday December 26, 2023 @09:56AM (#38772252)
The tutorial starts with

    cout << "Hello, World!" << '\n';
But the most "modern" way to write to the console is:

    std::println("Hello World!");
Re:Learn Modern C++ by bdw5204 on Tuesday December 26, 2023 @12:01PM (#38773495)
What is the rationale behind changing how print statements work in C++? Is there something broken about using cout or is this just another case of C++ adding extra ways to do the same thing for the sake of adding extra ways to do the same thing?

The only significant difference I see is that std::println automatically includes the newline which may or may not be desired behavior.

Re:Learn Modern C++ by steveklabnik on Tuesday December 26, 2023 @12:11PM (#38773592)
What's fun is, because everything is decided in papers, we can find out why! https://github.com/cplusplus/papers/issues/884

Accepted paper here: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p20...

> The proposed std::print function improves usability, avoids allocating a temporary std::string object and calling operator<< which performs formatted I/O on text that is already formatted. The number of function calls is reduced to one which, together with std::vformat-like type erasure, results in much smaller binary code (see § 13 Binary code).

Additionally,

> Another problem is formatting of Unicode text:

> std::cout << "Привет, κόσμος!";

> If the source and execution encoding is UTF-8 this will produce the expected output on most GNU/Linux and macOS systems. Unfortunately on Windows it is almost guaranteed to produce mojibake despite the fact that the system is fully capable of printing Unicode

Re:Learn Modern C++ by gavinray on Tuesday December 26, 2023 @02:19PM (#38775008)
Whoever thought that the idiomatic approach to "Hello, World!" in their language ought to involve using special overloaded operators as symbols to act on pipes must've been on something very strange.
Re:Learn Modern C++ by steveklabnik on Tuesday December 26, 2023 @04:09PM (#38776081)
I don't disagree that iostreams feels like a mistake in retrospect, though you have to put yourself in the time period to understand why people make decisions the way that they do. Bjarne wrote the first version of that library in 1984! And it was moved into the standard in '98.

https://stackoverflow.com/a/4854358/24817 is the canonical explanation for why >> and <<, apparently. Nearby, this is also mentioned:

> C’s printf family of functions is an effective and often convenient I/O mechanism. It is not, however, type safe or extensible to user− defined types (classes). Consequently, I started looking for a type safe, terse, extensible, and efficient alternative to the printf family. Part of the inspiration came from the last page and a half of the Ada Rationale [Ichbiah,1979], which is an argument that you cannot have a terse and type− safe I/O library without special language features to support it. I took that as a challenge. The result was the stream I/O library that was first implemented in 1984 and presented in [Stroustrup,1985].

and

> The stream I/O facility is implemented exclusively using language features available to every C++ programmer. Like C, C++ does not have any I/O facilities built into the language.

The language simply didn't have the advanced tools that ended up being used in more modern solutions yet. It was too early.

Re:Learn Modern C++ by vitaut on Tuesday December 26, 2023 @07:48PM (#38777758)
It is weird but not unique to C++. For example, python used the % operator for string formatting. It's a simple but hacky way to feed arbitrary number of arguments in a type-safe way if you don't have variadics.
Re:Learn Modern C++ by gettodachoppa on Wednesday December 27, 2023 @07:41AM (#38781412)
I know you think this sounds like a good reason, but all I can think is that C++'s continues its mutation into a new language and adding to the developer's cognitive load, all for the purpose of a minor performance optimization. In what is already a very performant language.

As usual, C++'s priorities are wrong for anyone who's not writing an OS, web browser, game engine, or otherwise rare type of project.

Re:Learn Modern C++ by steveklabnik on Wednesday December 27, 2023 @09:51AM (#38782463)
I agree with you that evolving languages that have been around for a long time is very difficult, with hard tradeoffs and unclear answers.

I think calling formatted printing “cognitive load” is a bit much though. If anything this is easier to understand and use than stdio and iostreams. It’s closer to other languages in this area. I probably would have voted yes on this if I were on the relevant committee.

Re:Learn Modern C++ by einpoklum on Tuesday December 26, 2023 @12:21PM (#38773700)
There are numerous shortcoming of the previous (iostreams) approach:

1. Incompatible with dynamically-generated format strings, in which the order of arguments is different. Example:

   std::cout << month << '/' << day << '/' << year
... but you now want to adapt that for a non-US locale, e.g. a European one where it's

   std::cout << day << '/' << month << '/' << year
with iostreams, you have to change the code. With C-style printf, you don't (but it's not typeafe and not flexible. But with std::print it could be:

   std::printf(my_format_str, day, month, year);
and `my_format_str` could be either "{0}/{1}/{2}" or "{1}/{0}/{2}".

2. The string allocations which other have mentioned.

3. A lot more typing that is easy to confuse: " << ".

4. The iostreams implementation is super-baroque, with buffer classes nobody uses.

and maybe I'm forgetting things.

Re:Learn Modern C++ by AtlasBarfed on Tuesday December 26, 2023 @06:30PM (#38777224)
Std:so std:you std:mix std:iosteam std:and std:printf?

Std:seems std:confusing

Re:Learn Modern C++ by okdood64 on Tuesday December 26, 2023 @12:17PM (#38773658)
There's std::print
Re:Learn Modern C++ by maccard on Tuesday December 26, 2023 @12:04PM (#38773522)
iostreams were a mistake, is the shortest way to sum it up.
Re:Learn Modern C++ by f1shy on Tuesday December 26, 2023 @02:23PM (#38775050)
Absolutely! Glad to see it ending
Re:Learn Modern C++ by vitaut on Tuesday December 26, 2023 @07:19PM (#38777572)
Did you mean endling?
Re:Learn Modern C++ by pauljurczak on Wednesday December 27, 2023 @03:34AM (#38780153)
No, he meant backslashend.
Re:Learn Modern C++ by pjmlp on Tuesday December 26, 2023 @04:50PM (#38776466)
Not for everyone, iostreams are great.
Re:Learn Modern C++ by icedchai on Tuesday December 26, 2023 @01:17PM (#38774294)
20 years ago, I worked on a fairly large C++ code base. Nobody used iostreams even then. We used C-style stdio everywhere. You can still do that.
Re:Learn Modern C++ by pjmlp on Tuesday December 26, 2023 @04:50PM (#38776452)
I have been using iostreams since 1993, they were never the cause for performance problems we actually had to solve.
Re:Learn Modern C++ by surajrmal on Wednesday December 27, 2023 @01:00AM (#38779497)
You've never had to deal with binary size concerns I suppose.
Re:Learn Modern C++ by pjmlp on Wednesday December 27, 2023 @04:28AM (#38780425)
You never coded for MS-DOS and Amiga, I suppose.
Re:Learn Modern C++ by vitaut on Tuesday December 26, 2023 @07:17PM (#38777554)
Glad you asked. I recently wrote a post about it: https://vitaut.net/posts/2023/print-in-cpp23/.
Re:Learn Modern C++ by andrepd on Tuesday December 26, 2023 @09:04PM (#38778290)
As you may imagine, the rationale behind offering a new way to do formatted output is not evidenced in a hello world statement.......

You can answer your own question if you google "println cppreference".

Re:Learn Modern C++ by beached_whale on Tuesday December 26, 2023 @11:33AM (#38773220)
That doesnt work on a majority of systems yet. Heck, gcc 14 gets it in the 14.1 release next year.
Re:Learn Modern C++ by pauljurczak on Wednesday December 27, 2023 @03:39AM (#38780176)
True. This is not a modern C++. It is a futuristic C++. Use {fmt} library in the meantime.
Re:Learn Modern C++ by beached_whale on Wednesday December 27, 2023 @04:41AM (#38780469)
I feel modern c++ is not so much mew features, save a few like move, but embracing guarantees with things like raii types.
Re:Learn Modern C++ by nalgeon on Tuesday December 26, 2023 @10:19AM (#38772460)
Maybe one day someone will rate all "Modern C++" tutorials according to their level of modernity :)
Re:Learn Modern C++ by dataflow on Tuesday December 26, 2023 @10:49AM (#38772767)
It's like modern art at this point, anything from the 1800s qualifies.
Re:Learn Modern C++ by pjmlp on Tuesday December 26, 2023 @12:16PM (#38773643)
We are already on post-neo-modernism.
Re:Learn Modern C++ by timeon on Tuesday December 26, 2023 @02:42PM (#38775265)
Maybe 'contemporary' would be better for this context.
Re:Learn Modern C++ by pokler on Tuesday December 26, 2023 @10:36AM (#38772640)
This is from C++23, right? I wonder how available this is within compilers and how many shops plan on moving to this version of the standard and how long that will take.

I imagine targeting C++17 or 20 for 'modern' would be practical enough considering thats what you are most likely to run into in a professional setting.

Re:Learn Modern C++ by steveklabnik on Tuesday December 26, 2023 @12:15PM (#38773640)
> This is from C++23, right?

std::println is, yes.

> I wonder how available this is within compilers

https://en.cppreference.com/w/cpp/compiler_support says clang, gcc, and msvc all support it, though I don't know how recent those versions are off the top of my head.

In my understanding, with this specific feature, if you want a polyfill for older compilers, or to use some more cutting-edge features that haven't been standardized yet, https://github.com/fmtlib/fmt is available to you.

Re:Learn Modern C++ by wiseowise on Tuesday December 26, 2023 @01:27PM (#38774409)
> says clang, gcc, and msvc all support it, though I don't know how recent those versions are off the top of my head

Where did you find it? Search by println yields no results.

Re:Learn Modern C++ by steveklabnik on Tuesday December 26, 2023 @01:36PM (#38774532)

  Formatted output library <print>
Re:Learn Modern C++ by wiseowise on Tuesday December 26, 2023 @02:12PM (#38774916)
Thanks!
Re:Learn Modern C++ by scatters on Tuesday December 26, 2023 @03:27PM (#38775703)
> I don't know how recent those versions are

gcc 14 has not yet been released; going by past years, 14.1 should come out around the start of May (2024). clang 17 was released September (2023); note that you need to use libc++ (stlib=libc++), not libstdc++. VS 2022 17.7 has been out since August.

Re:Learn Modern C++ by steveklabnik on Tuesday December 26, 2023 @03:49PM (#38775916)
Thank you!
Re:Learn Modern C++ by materielle on Tuesday December 26, 2023 @03:23PM (#38775671)
Honestly C++ is in a real pickle.

So iostreams were a mistake, they shouldn’t have happened in the first place. And given that they happened, std::format should have been added 20 years ago, or at least in C++11.

The problem is that many professional shops never used iostreams, and instead hand rolled their own format library. Now, they don’t really care about std::format, and probably will never use it, because it would involve migrating off of their hand rolled solution which is working great.

On the other hand, for small shops and hobbyists that don’t have the resources to reimplement std, this is a huge quality of life improvement. Meanwhile, more modern languages like Rust are encroaching.

And this is all just about how to print “Hello World!”. This situation is really emblematic of the challenges faced by the C++ committee. It is really impossible to please everyone, or even a majority, since the community is so fractured.

Re:Learn Modern C++ by vitaut on Wednesday December 27, 2023 @11:46AM (#38783764)
This is not about printing hello world but about all formatted I/O which is a significant chunk of the library. To be fair formatted I/O is pretty broken in C as well but for completely different reasons.
Re:Learn Modern C++ by tejohnso on Tuesday December 26, 2023 @11:00AM (#38772888)
I immediately thought your critique would be to use std::endl instead of '\n'

I was reading a lot of c++ core guidelines and modern c++ blogs and books while writing a little game a couple of years ago and std::println was definitely not the common suggestion for modern c++. I see it's probably because it wasn't even available at the time. Now I feel like I'd have to review everything that I thought was modern two years ago to confirm that it is still the modern way.

Re:Learn Modern C++ by maccard on Tuesday December 26, 2023 @12:18PM (#38773671)
\n is a newline, endl is \n plus flushing stdout.
Re:Learn Modern C++ by jb1991 on Tuesday December 26, 2023 @11:39AM (#38773272)
std::endl is actually not advised most of the time. Using \n is the better alternative unless you need a buffer flush.
Re:Learn Modern C++ by dundarious on Tuesday December 26, 2023 @02:33PM (#38775175)
If stdout is going to a terminal (i.e., it hasn't been redirected to a file), then the standard library will by default flush on every '\n' anyway. Similarly for C with fputs, etc.

In C you control this with setvbuf, and of course, in C++ with iostreams it's a huge mess of rdbuf spaghetti and probably involving std::ios_base::sync_with_stdio as well.

Re:Learn Modern C++ by fooker on Tuesday December 26, 2023 @05:05PM (#38776600)
This is wrong, stdout is not flushed by default on every newline.

You can observe this by printing out tens of thousands of lines with vs without explicit flushing, there will be a big performance difference.

Re:Learn Modern C++ by dundarious on Wednesday December 27, 2023 @01:12PM (#38784717)
Edit: My C preference and iostream hatred is showing again, because I answered a question that was mostly about C++ iostreams with results based around C stdio (I think iostream is possibly the worst standard IO API in existence for a popular language, so when using C++, I recommend using something custom calling out to OS syscalls or C stdio). I could easily be wrong about C++ iostreams, so the most relevant half of my original post is highly suspect. I'll test it out later, but my C stdio answer is as-is below.

I've tested that I'm correct on glibc, where the behavior is documented here: https://www.gnu.org/software/libc/manual/html_node/Buffering...

I can't remember using an alternative platform that behaves differently.

A better test than the one you ran is to look at the resulting syscalls from a loop of `fputs("a line of output.\n", stdout);`, vs. `fputs("a bit of output. ", stdout);`. Buffering accumulates strings in memory before an eventual write syscall, so looking at syscalls is an easy way to see the difference: a write per-'\n' means line buffering.

Compare the syscalls of both using strace. I did so, and when stdout is to the terminal, I see lots of calls to `write(1, "a line of output\n", 17)` compared to `write(1, "a bit of output. a bit of output"..., 1024)`. (To confirm, manually insert an `fflush(stdout);` in the "a bit of output. " version, and you'll see lots of `write(1, "a bit of output. ", 17)`)

Then compare both when redirecting stdout to a file, and you'll see both cases make large write-s of 4KB. Only adding explicit fflush-es will make either version go back to small write-s of 17B.

Compiled the trivial test programs with `cc -O2 ./main.c -o ./main`

Re:Learn Modern C++ by dundarious on Wednesday December 27, 2023 @02:56PM (#38785893)
Tested g++/libstdc++ and clang++/libc++ and both operate identically to the C test above, testing `std::cout << "a line of output\n";` vs. `std::cout << "a bit of output. ";` (and with explicit flushes using `std::cout << "a line of output" << std::endl;` and std::cout << "a bit of output. " << std::flush;).

So I'm correct on those targets as well.

Re:Learn Modern C++ by fooker on Wednesday December 27, 2023 @09:56PM (#38789486)
This is wrong.

Looking for write syscalls is not a valid way to figure out where buffering is happening.

Write by default is famously buffered in Linux, and stdio/iostresm functions map closely to it. So, if you call these C functions N times, you'll see write being called N times.

Flushing calls fsync or some ioctl depending on the file descriptor is, iirc.

Re:Learn Modern C++ by dundarious on Saturday December 30, 2023 @10:25AM (#38815927)
fflush and std::endl/std::flush are not synonymous with the fsync syscall. None of the standard libraries I tested above call fsync at all when using those functions. They flush the accumulated memory "to the file" in the sense of making a write syscall (or equivalent, e.g., writev), and they do not attempt to enforce a flush to disk, that's just left to the OS. The "line buffering" in question is the C/C++ library accumulated memory, and the relevant kind of "unbuffering/flushing" is just write-like syscalls.

I meant to reply much sooner, with more info from empirical tests. But now I'm happy to leave it at just the write stuff and the note about the meaning of stdio/iostream "flushing".

I think you have an incorrect or esoteric understanding of what the "buffering" in question is, but it doesn't matter to me. My argument is about what syscalls happen, and I don't care if you disagree with the (I think, standard) descriptor/terminology I'm using.

Re:Learn Modern C++ by jpcfl on Tuesday December 26, 2023 @03:11PM (#38775564)
> I was reading a lot of c++ core guidelines and modern c++ blogs and books while writing a little game a couple of years ago and std::println was definitely not the common suggestion for modern c++.

Probably because it has only been available since C++23: https://en.cppreference.com/w/cpp/io/println.

Re:Learn Modern C++ by einpoklum on Tuesday December 26, 2023 @12:11PM (#38773593)
That's the modern-modern C++ :-)

More seriously, though - the language is changing gradually: Features are introduced (and rarely, deprecated); and the missing bits of the standard library are added. C++11 was a _very_ significant change - but not to how you print output. C++20 and C++23 introduced `std::format` and `std::print`.

Re:Learn Modern C++ by angiosperm on Tuesday December 26, 2023 @02:13PM (#38774934)
C++20 is as big a change as C++11. It is almost as much more pleasant upgrading to C++20 as was upgrading to C++11. As more of the C++20 features get implemented in the compiler you use, the experience will continue to improve.

Many people can already write "import <std>;" instead of many lines of "#include <...>".

Re:Learn Modern C++ by NekkoDroid on Tuesday December 26, 2023 @02:36PM (#38775199)
its `import std;`, without the angled brackets. Just make sure you are using the namespaced fixed integer types if you do :) else you still need `import std.compat` which is basically the c-headers
Re:Learn Modern C++ by gdiamos on Tuesday December 26, 2023 @10:45AM (#38772731)
When did that happen? I used to write a lot of C++, but it's been years since I've had to use it everyday.
Re:Learn Modern C++ by jenadine on Tuesday December 26, 2023 @11:33AM (#38773214)
This year (C++23)
Re:Learn Modern C++ by pauljurczak on Wednesday December 27, 2023 @03:40AM (#38780180)
It has not happened yet...
Re:Learn Modern C++ by tobinfricke on Tuesday December 26, 2023 @12:37PM (#38773855)
Very Pascal-esque
Re:Learn Modern C++ by moffkalast on Tuesday December 26, 2023 @01:24PM (#38774374)
God forbid it actually figures out what the type is and prints it out properly like every other language in existence? If so I'm sold.
Re:Learn Modern C++ by bingo3131 on Tuesday December 26, 2023 @02:07PM (#38774862)
Yes. The main feature this is built upon is C++20's new string formatting features (very heavily inspired by the third party libfmt). C++23 just adds convinience functions to format and print at the same time.

Type detection, formatting options, positional-arguments, custom formatters for custom types and probably more are all supported.

Re:Learn Modern C++ by UncleOxidant on Tuesday December 26, 2023 @01:50PM (#38774664)
This comment right here is modern C++ in a nutshell. The most "modern" way will likely be different next year.
Re:Learn Modern C++ by angiosperm on Tuesday December 26, 2023 @03:59PM (#38776014)
But either way is fine.
Re:Learn Modern C++ by fsloth on Tuesday December 26, 2023 @02:17PM (#38774973)
You don’t need to keep up with the joneses to write C++. The whole point with the language is that it’s for millions of lines of code that exist for decades and you don’t update every line every time the standard is updated.

Most existing code probably uses output streams with << operators, it’s good to know what that does.

Re:Learn Modern C++ by f1shy on Tuesday December 26, 2023 @02:27PM (#38775095)
I‘ve hated cout from day 0. happy to learn this. Thanks!
Re:Learn Modern C++ by inetknght on Tuesday December 26, 2023 @02:29PM (#38775122)
> But the most "modern" way to write to the console is:

Indeed, as mentioned [0] at cppcon 2022 :)

[0]: https://youtu.be/eD-ceG-oByA?list=PLHTh1InhhwT6c2JNtUiJkaH8Y...

Re:Learn Modern C++ by 3836293648 on Tuesday December 26, 2023 @03:12PM (#38775570)
Sure, but that still doen't have compiler support in compilers people actually have
Re:Learn Modern C++ by pjmlp on Tuesday December 26, 2023 @04:48PM (#38776438)
Not for portable code, C++23 is still quite far from being widely available.