3

I'm struggling to understand pros and cons of the C++ and C approaches to console output. C++ uses the stream approach with concatenation of operator<<, while for "C approach" I mean a print function taking as arguments a string with placeholders and values to be substituted to placeholders.

While I like the C++ approach I see that many logging libraries for C++ (e.g. spdlog) use the C approach; this makes me think that something with the C++ approach might be considered wrong by several people, but I cannot figure out what.

1
  • 1
    The c++ approach adds a new one on the top of the C one. Whether which one is most beneficial is for you to evaluate, on a case by case basis. Commented Feb 8, 2024 at 16:54

1 Answer 1

8

The printf() approach has these disadvantages:

  1. No type-safety. Some compilers add some type-safety their own way, at least when the format-strings are known.

  2. No extensibility. Only the basic types baked in are understood and can be formatted. Thus, some projects bake their own. Yet again, some libraries have a way for limited dynamic extending, but that's both a global solution for a local problem, and not portable.

  3. No indexed parameters. Yet again, there are extensions in some common libs.

The <iostream> approach has its own disadvantages:

  1. No replaceable format-string.
  2. More verbose.
  3. It's a long chain of operators and operands, and thus cannot be forwarded.

In order to take the advantages of both and avoid the disadvantages of either, C++ added something new, though it builds on the latter: <format>

  1. It is type-safe and extensible.
  2. It uses a format-string with indexed arguments.
1
  • This is pretty much the kind of information I was looking for, thank you. Commented Feb 8, 2024 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.