Printf' Vs. 'Cout' in C++

cout vs printf C++

cout is the C++ version of printf. printf requires you to specify the type, cout does not. printf is generally faster as well. So cout is not so fast but easy, and printf is fast, but not way to easy if you are not familiar with it. When using c++, cout should be used, unless you need printf. I prefer cout because it is type-safe (big thing!), and it is more c++ish (if that makes sense).

Notes:

  • printf is in stdio
  • printf came from c
  • printf is not type safe!

difference between printf() and std::cout with respect to pointers

The format specifier %p prints a void *, (untrue: so the char * is implicitly converted to void *) the char * is converted to void * before printing. (But this is actually undefined behavior, see comments. The correct way to do that would be printf("%p", (void *) str1);) The corresponding C++ code would be std::cout << (void *) str1 << '\n';.

The code std::cout << str1; prints str1 as null terminated string. The corresponding C-code would be printf('%s', str1);

Should I use printf in my C++ code?

My students, who learn cin and cout first, then learn printf later, overwhelmingly prefer printf (or more usually fprintf). I myself have found the printf model sufficiently readable that I have ported it to other programming languages. So has Olivier Danvy, who has even made it type-safe.

Provided you have a compiler that is capable of type-checking calls to printf, I see no reason not to use fprintf and friends in C++.

Disclaimer: I am a terrible C++ programmer.

printf vs cout performance

I don't have VS 2010 installed any more, but I did a quick test with VS 2013 and 2015. I modified your code slightly to reduce duplication, and include timing code, giving this:

#include <iostream>
#include <cstdio>
#include <chrono>
#include <string>

template <class F>
int perf(F f) {
using namespace std::chrono;

const int count = 1000000;
char a[100] = "fosjkdfjlsjdflw0304802";

auto start = high_resolution_clock::now();
for (unsigned i = 0; i < count; i++)
f(a);
auto end = high_resolution_clock::now();

return duration_cast<milliseconds>(end - start).count();
}

int main() {
std::cerr << "cout: " << perf([](char const *a) { std::cout << a; }) << "\n";
std::cerr << "printf: " << perf([](char const *a) { printf("%s", a); }) << "\n";
}

With optimization turned off, cout showed up as slightly faster (e.g., 358 ms vs. 460 for printf) but measuring speed with optimization turned off is fairly meaningless.

With optimization turned on cout won by an even larger margin (191 ms vs 365 ms for printf).

To keep these meaningful, I ran them all with the output redirected to a file. Without that, essentially all you'd measure would be the speed of the console driver, which is essentially meaningless and worthless.

printf/scanf usage and difference from iostream and cout/cin diffferences, when to use which?

Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”.

cin/cout is faster than scanf/printf, key differnce among these.

Why is scanf faster than cin?

On a high level both of them are wrappers over theread() system call, just syntactic sugar. The only visible difference is that scanf() has to explicitly declare the input type, whereas cin has the redirection operation overloaded using templates. This does not seem like a good enough reason for a performance hit of 5x.

It turns out that iostream makes use of stdio‘s buffering system. So, cin wastes time synchronizing itself with the underlying C-library’s stdio buffer, so that calls to bothscanf()and cin can be interleaved.

The good thing is that libstdc++ provides an option to turn off synchronization of all the iostream standard streams with their corresponding standard C streams using

std::ios::sync_with_stdio(false);

same with cout and printf.

but in simple words, cin, cout uses extraction and insertion in c++ which are basically overloaded, hence another factor of slow speed.

I hope this answer your question of why one is preferred over another and they are basically the way to input data, and internally cin, cout is written using c stdio buffer library.

cout vs printf when doing fork()

When you use stdio, stdout is fully-buffered unless it's writing to a terminal; when writing to a terminal it's line-buffered.

So if you run Program 1 with output redirected to a file or pipe, printf writes the line to the output buffer, but doesn't flush the buffer. When the process forks, the buffer is duplicated in both processes. When they exit, they each flush their copy of the buffer, which prints the line.

You would get the same result in Program 2 if you'd written:

cout << "Hi , " <<getpid() << "\n";

But endl, in addition to outputting the newline character, also flushes the buffer. The equivalent in Program 1 would be:

printf("Hi , %d\n" , getpid());
fflush(stdout);


Related Topics



Leave a reply



Submit