r/cpp • • Aug 31 '21

[Belay the C++] Yet another reason to not use printf (or write C code in general)

https://belaycpp.com/2021/08/31/yet-another-reason-to-not-use-printf-or-write-c-code-in-general/
0 Upvotes

49 comments sorted by

48

u/initplus Aug 31 '21

I'm not necessarily convinced by this argument. Every modern C++ compiler produces warnings if printf arguments don't match the format string, even if printf API itself doesn't enforce it.

Yes you have to enable -Wall but honestly you should have compiler warnings enabled anyway.

28

u/peppedx Aug 31 '21

Just use https://github.com/fmtlib/fmt It's a no brained. Faster, safer mare ergonomic

1

u/nintendiator2 Aug 31 '21

Haven't been able to make it work with MSVC 2012 (the earliest Windows-side compiler I need to support). I myself use tinyformat instead.

3

u/adjective-ass-noun Aug 31 '21

alright, I'll bite since I'm curious, what's your use-case that you still need to support MSVC 2012?

4

u/nintendiator2 Sep 02 '21

Work. Sometimes, it's as simple as that.

(Mind, we advanced it a lot. The original toolkit for those applications was in VB 6 + VC 2008 SP1. The idea was to move them to somewhat newer stuff that was proven to not break and was supported by some third party components that are needed, so that maintenance was a bit easier and performance a bit better until the time comes when we can phase out the software. Which is in $UNKNOWN fiscal years, last I checked)

-16

u/Senua_Chloe Aug 31 '21

Nice, though 3rd-tier

17

u/peppedx Aug 31 '21

It has been standardized in C++20.

I use it in each project even embedded.

1

u/[deleted] Aug 31 '21

You must use fmtlib because c++20 does not provide an implementation of fmt::print

17

u/peppedx Aug 31 '21

Sure but calling fmtlib 3d tier seems ingenerous to me

0

u/[deleted] Aug 31 '21

[deleted]

14

u/aearphen {fmt} Aug 31 '21

Compile times are actually comparable to printf's + <string> header included: https://github.com/fmtlib/fmt#compile-time-and-code-bloat. With modules the latter which is a fixed per-TU cost will go away and even now <string> is likely included transitively anyway.

0

u/[deleted] Aug 31 '21

[removed] — view removed comment

3

u/dodheim Aug 31 '21

That you can be type-safe without being redundant is basically the point of the library..

1

u/AlexAlabuzhev Aug 31 '21

I don't like it, because you are not required to specify the expected types of the argument

But why? It's the best thing about it.

0

u/[deleted] Sep 01 '21

[removed] — view removed comment

2

u/AlexAlabuzhev Sep 02 '21

none allow to also specify the type of what you want

Still, why do you want to specify the type explicitly? Manipulation of output does not require that. If I want to format a number as hex, I write {:x} and it works with any integer. Why would I care to specify whether it's short or int or unsigned long long or something else?

nobody would remember or guess the actual format string for this case

The same applies to printf and any other format specifiers: nobody would remember or guess what %-#012.3f means, it has to be looked up every time.

2

u/RogerLeigh Scientific Imaging and Embedded Medical Diagnostics Sep 02 '21

The common case is clearly to format the output using the same type as the input value's type. You don't need to specify this information redundantly.

If you do need to format as a different type, why would you need the format string to provide this functionality. Why not just typecast the input value to the output type you desire?

2

u/Dalzhim C++Montréal UG Organizer Sep 02 '21

I used to think the modern compiler warnings would protect me, until I found out some homegrown string classes had printf forwarding methods. Sure enough, those ended up being misused without any warnings.

-9

u/Senua_Chloe Aug 31 '21

You don't always have a hold on the option of the compiler your project is using. Plus, some devs (your infamous coworkers) don't care about warnings.

19

u/initplus Aug 31 '21

Sure.

But honestly if you are not enabling at least a minimal set of warnings on your project bugs with printf types are likely to be the least of your worries.

Regarding coworkers who don't care, are they going to care about rules like "don't use printf" either? Whatever you agree on for code quality standards, it needs to be enforced.

5

u/zeldel Aug 31 '21

If you are working in an environment where warnings are accepted and not taken care of, then you most likely have:
A) the wrong setup, as it should be set "warning as errors", in basically any production-level project

B) No power, to enforce any coding standard

I've worked in outsourcing for a while, therefore I know that some things can be really messed up - yet! At least warnings were never the case in my projects.

4

u/m-in Aug 31 '21

Now your reason boils down to “but coworkers”. That makes the whole long winded article a bit moot. You’re shifting goalposts, and that’s a technique that everyone who can’t argue their way out of a paper bag uses. It’s repulsive. Don’t expect to be treated seriously when your tactic makes them go “yuck”.

0

u/RoyBellingan Aug 31 '21

Warning ?
I created a function called seppuku that is called in local enviroment to force crash the program on warning...

Before having the program spitting red line all over the place was a minor nuance.

1

u/Senua_Chloe Aug 31 '21

Talking about compilation warnings here

You can always activate -Werror if you like

5

u/_kst_ Sep 01 '21 edited Sep 01 '21

The article claims (referring to calling printf with a %d format and a double argument):

This actually generates a warning with clang. But with gcc, you’ll have to activate -Wall to see any warning about that.

That's not correct as of gcc 9.3.0. Both gcc and g++ produce a clear warning message with no special options:

warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]

UPDATE It appears I was mistaken. Enabling -Wformat by default is an Ubuntu-specific configuration, not a feature of the default gcc.

1

u/Senua_Chloe Sep 01 '21

From your prompt it looks like the warning is comes from -Wformat.

5

u/_kst_ Sep 01 '21

Yes and no. The message indicates that -Wformat can be used to enable or disable the warning, but I ran gcc and g++ with no options other than -o, so apparently the warning is enabled by default.

However, I've just done a little more investigation. gcc 9.3.0 built from source doesn't enable the warning by default, but the gcc 9.3.0 that comes with Ubuntu 20.04 does.

So enabling -Wformat by default is an Ubuntu-specific configuration, not a default behavior of gcc.

18

u/zeldel Aug 31 '21

Apart of the `printf` issue. You have stated at the end

That is exactly why I always deny job offers that have the tag “C/C++” because they obviously can’t pick a side.

This is simply foolish. Sometimes you are not able to pick a side, especially if you are dealing with embedded and supporting various platforms. Those platforms will most likely have their API/toolchain written in C - there might be tons of reasons, historical as a starter.

Then as a developer, your main focus is creating a proper layer in C++, yet you still need to write/read C code. No sain person is probably mixing those on modules level, within the same scope. Unless there is a very clear reason to do so. Sometimes safety features (ASIL) are written in C.

7

u/pjmlp Aug 31 '21

Apparently the author doesn´t want to work at most companies that take seat at ISO C++ table, given the usage of C/C++ across their product documentation.

6

u/thedeadfish Aug 31 '21

don’t use printf

Of all the things one could complain about he picks something so trivial. If programmers are so incompetent now that they can't even use printf correctly, then that would explain the state of modern computing.

9

u/Orlha Aug 31 '21

If it's possible to use fmtlib in the project, I'm going to use it.

If not, then I use a printf-family, but a sad-face will be apparent.

14

u/victorofthepeople Aug 31 '21

"Hai guys cout << reinterpret_cast<double>(69) prints something that's not 69, therefore don't use iostream and especially don't use c++"

3

u/vax_mzn Aug 31 '21

iostream is slow though.

4

u/NilacTheGrim Aug 31 '21

Often slower than untyped printf...

If you wanted a typed thing, and you care about performance, avoid iostream.

2

u/pepitogrand Sep 02 '21

Not at all, use std::cout::sync_with_stdio(false)and execute your benchmarks again.

0

u/vax_mzn Sep 02 '21

It will still be slower but not as worse for sure. Also how many people know about this?

1

u/eyes-are-fading-blue Aug 31 '21

Isn’t using wrong format specifier UB? I think this is a symptom of a greater issue with C and C++ where sometimes it is too easy to make mistakes.

The goos thing is that this is can be detected with some sort of lint tool.

11

u/[deleted] Aug 31 '21

[removed] — view removed comment

13

u/NilacTheGrim Aug 31 '21

Well this "Belay the C++" series is just low quality content if you ask me.

8

u/guepier Bioinformatican Aug 31 '21 edited Aug 31 '21

IIRC the author is not a native speaker (the nonsensical/ungrammatical title of the blog is a bit of a hint), cut them some slack. That said, it’s true that the articles are generally not of very high quality, with regards to either language or contents.

4

u/NilacTheGrim Aug 31 '21

nonsensical title of the blog is a bit of a hint

Yeah the title is a bad choice. I agree.

From merriam-webster.com:

Belay : (1) to secure (a rope or cable) by turns around a cleat (see CLEAT entry 1 sense (1b), pin, or bitt b: to make fast : to fasten down -- "belaying ammunition on deck"

(2) nautical : STOP, CANCEL -- "belay that last order"

Most native English speakers are familiar only with the nautical (2) definition from things like Star Trek.

So when I hear "Belay the C++" --> my brain thinks "cancel the C++". Which I'm pretty sure is not what the author intended.

3

u/evaned Aug 31 '21

Most native English speakers are familiar only with the nautical (2) definition from things like Star Trek.

With the moderate popularity of rock climbing -- it's even in the olympics now -- I wonder if this is true.

(That's definition (3) on merriam-webster.com, but is pretty close to (1).)

1

u/NilacTheGrim Sep 01 '21

Oh maybe. I don't know anything about rock climbing. Maybe it's very popular...

5

u/guepier Bioinformatican Aug 31 '21 edited Aug 31 '21

I know what “to belay” means but the definite article (”the”) doesn’t fit here, and even “belay C++” just sounds off — partly, I suppose, because “belay” really has a ton of quite different meanings, and without seeing the site’s logo (which makes the context clear because it includes a climbing carabiner), the title really is impossible to parse. Case in point: given the logo, the intended meaning is almost certainly neither of the ones you quoted (although it’s close, and closely related, to the first one).

0

u/NilacTheGrim Aug 31 '21

Ah insightul.

As for the the: Hmm. Well, I'm a native speaker, but from NYC and a lot of people that I know add "inappropriate" definite articles to exaggerate a thing or make it out to be disproportionate in some way. Consider the sentence: "So you've been learning the C++?" versus "So you've been learning C++?". You'd use the former, perhaps, to highlight some in-joke between you and the person you are talking to. Whereas the latter would be more emotionally neutral and would not betray any bias in any direction.

So I interpreted "Belay the C++" as in "Secure the (problematic, hard, important) C++"

shrug

2

u/_kst_ Sep 01 '21

I don't see the word "registry" anywhere in the article. Perhaps it was updated?

3

u/m-in Sep 01 '21

That’s the perfect outcome. Thank you for noticing! My job here is done.

1

u/foonathan Sep 02 '21

It won't hurt you to say that nicer in the future.