16

I have read three ways to print things to the console in c++ from various sources.

  1. Using using namespace std; and then using cout (CodeBlocks Standard)
  2. Not using the above and using std::cout and std::endl; (C++ Primer)
  3. Using printf (HackerRank)

Which is preferred and why?

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
Devesh Lohumi
  • 362
  • 2
  • 15
  • 3
    Both 1 and 2 are really the same. And using `printf` isn't type-safe. – Some programmer dude Jun 13 '18 at 10:52
  • 4
    Possible duplicate of ['printf' vs. 'cout' in C++](https://stackoverflow.com/questions/2872543/printf-vs-cout-in-c) –  Jun 13 '18 at 10:52
  • 1
    I don't suggest using `using namespace std;` unless it's for a small project. You're likely to cause ambiguities. Since it's c++ `std::cout` is what people usually go for. – Qubit Jun 13 '18 at 10:52
  • 15
    Please, pretty please, do not try to learn C++ from hackerrank. That would ende ***very*** poorly. – Baum mit Augen Jun 13 '18 at 10:52
  • 4
    See also: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice –  Jun 13 '18 at 10:52
  • 1 and 2 are a matter of style, and context dependent as to when one would be used over the other. 3 is not strictly C++, but _also_ has it's place. There are major drawbacks to variable argument functions (like `printf`) though. – Chad Jun 13 '18 at 10:52
  • In c++ use option 2. – Robert Andrzejuk Jun 13 '18 at 10:52
  • For option 1 read : https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice#1452738 – Robert Andrzejuk Jun 13 '18 at 10:54
  • 4
    It is bad practise to use `using namespace std` at global scope because of namespace pollution (see [here](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)) – David Jun 13 '18 at 10:55
  • one advantage of `printf` that isn't talked about is the internal locking witch make it better then `std::cout` for multi-thread programs – Tyker Jun 13 '18 at 11:18
  • @JeJo What is a good alternative for practice along with learning theory ? – Devesh Lohumi Jun 13 '18 at 11:31
  • 1
    To those closing this question as primarily opinion based, this question has a distinct answer. It is not opinion based at all. – Fantastic Mr Fox Jun 13 '18 at 11:34
  • Short answer: none of the above. C++ doesn't have a concept of "console". I'd suggest that `std::clog` (or `std::wclog`) is likely to be the closest approximation. – Toby Speight Jun 21 '18 at 13:09

5 Answers5

22

Number 2 with amendment. (std::cout and '\n')

Why?

  1. Because you should avoid using namespace std. Source
  2. (Among other reasons) Because cout is typesafe and printf is not. Source
  3. std::endl will force a flush of the output buffer to the console. Unless you specifically want this to happen use << '\n' or << "...string\n". Source
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
6

Unless you really care about speed, both cout and printf are fine. If you want faster runtimes, here are a few pointers :

  • Use only printf with no cout. This will give more speed than using a mixture of printf and cout or just cout.
  • Or use only cout but add the following at the beginning of execution ios_base::sync_with_stdio(false);cin.tie(NULL); . There are two separate streams for printf and cout and they are synchronized by default. Lot of running time is wasted due to this synchronisation. These two lines of code will stop the synchronisation, but take care that you don't use any printf if you add these lines, otherwise printing might happen in random order.
  • Do not use endl unless you want to flush the output buffer. Lots of endl can make the code slower. Use cout<<'\n'; instead.
1

Both your first points do basically the same thing. It's better practice to use std:: instead of using namespace std; as the latter pollutes the global namespace and can cause naming conflicts.

Something not mentioned is that you can selectively expose parts of a namespace with using <namespace>::<element>; (e.g. using std::cout;). It's still better practice to be verbose with your statements, but this option still isn't as bad as exposing the entire namespace.

printf isn't as safe as cout (the stream << operators do a good job of printing what you want), you ought to avoid it while starting out.

Alex Meuer
  • 1,621
  • 3
  • 26
  • 37
  • Especially as beginner I would recommend not to use `using namespace std;` and specify `std::` each time, just to get used to reading code like that. But just as you stated, it can get highly opinionated. – KorbenDose Jun 13 '18 at 11:24
  • 1
    @AlexMeuer Putting `using namespace …` in a *header*, at namespace scope, is almost universally considered bad practice, though, just to be a bit more specific here. – Arne Vogel Jun 13 '18 at 11:26
1

these is my debugger code that during these 10 years of c++ working helped me.

std::ostream &debugRecord (const char* fileName, int lineNum, const char* funcName)
{
    std::lock_guard<std::mutex> lock(streamMutex_);
    return std::cout << "Thread # " << getCurrentThreadId() << " -- "
                     << "(" << fileName << ":" << lineNum << "): " << funcName << std::endl;
}
SHR
  • 7,940
  • 9
  • 38
  • 57
Ehsan Panahi
  • 130
  • 5
  • 1
    printf did not do it very well for me and confused me so i do it with cout and get good results. also << operation help very much – Ehsan Panahi Jun 13 '18 at 11:33
  • You should mention which headers you need for the concurrency API you use (where does `getCurrentThreadId()` come from?) – Peter - Reinstate Monica Jun 19 '18 at 08:22
  • getCurrentThreadId() is function which i write it before. but if you need it tell me to write it here for you. – Ehsan Panahi Jun 19 '18 at 12:58
  • No, not necessary; but you should mention that in the answer and make it obvious that your code is just a proposal or template, nothing which can directly be copied and pasted. I liked it though, even if the OP's question was probably more general. – Peter - Reinstate Monica Jun 19 '18 at 13:29
  • Why are you using `std::cout` for debugging, instead of `std::clog` (which is provided for *exactly* that purpose)? You really don't want your logging mixed up with your program output! – Toby Speight Jun 21 '18 at 13:10
1

The answer depends a lot on what you want to do. For output which largely uses default formats cout is indeed preferred because of the type safety and because it's very intuitive.

If you want to heavily format your output though I can only recommend the surprisingly versatile and straight-forward printf because manipulators in cout are a pain. True: The printf format syntax, does, let's say, take some getting used to, but it's surely worth it. Just double check the format string, listen to the warnings of your compiler, and use the proper format specifiers e.g. for size_t and other system dependent data in order to stay portable.

There is also a boost facility for combining streams and printf style formatting, see https://stackoverflow.com/a/15106194/3150802, but I have never used it. Perhaps somebody can comment on its usability?

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62