简体   繁体   中英

Use of printf in C++

A search of the site for "printf vs cout" turned up a discussion of the difference between the two, but that isn't what I was looking for. Coming from Python, I'm a huge fan of the way printf employs string formatting and I'd rather avoid cout if possible.

Is it considered bad practice to ignore cout and use printf exclusively? What would be the implications of doing this? What are some cases where using printf wouldn't be an option?

1) You can only use printf for fundamental types, and for integers it is really only usable for the "native" types int , long int etc. Something like uint32_t requires rather awkward and cumbersome macros for portable printing. User-defined types are not supported at all.

2) printf is not typesafe. That is, the correctness of your code depends on the value of the formatting string, and you cannot tell whether your program is well formed from static analysis alone. This is the fundamental weakness of the C typesystem, which "proper" C++ avoids.

That said, printf (or perhaps (v)snprintf , rather) is usually quite a bit faster than iostreams, so in a high-performance context (eg high-frequency logging) it is a very competitive alternative. However, if you just have occasional output operations, you should prefer iostreams, or some other flexible, typesafe, idiomatic C++ method. (And admittedly iostreams is probably one of the most terrible corners of C++.)

Is it considered bad practice to ignore cout and use printf exclusively?

No, if you prefer to use printf , go ahead.

What would be the implications of doing this?

None. The C++ way would be to use cout , because it's supposed to be simpler.

What are some cases where using printf wouldn't be an option?

I doubt you'll find such cases. If you do, people writing them are too subjective.

cout is type-safe. cout is an ostream and so it has the same interface as other ostream s - for instance you can provide new overloads for printing foo .

printf has format strings which occasionally are better than cout 's method of formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM