Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this output of the same expression from printf differ from cout?

I'm using Visual C++ 2012 and compiling from the command line the following files:

#include <stdio.h> int main() {     printf("%.5f", 18/4+18%4);     return 0; }  

Linking with MSVCRT.LIB rather than LIBCMT to avoid runtime error R6002.
The value that is output is 0.00000 for this program.

However, if I perform the exact same thing in C++

 #include <iostream>  using namespace std;  int main()  {       cout << 18/4+18%4 << endl;       return 0;  } 

Now, it prints out 6, like it should.

What's the difference? Is it to do with the languages themselves (C vs C++) or the output methods (cout vs printf), or is it just a quirk with MSVC?

like image 708
Govind Parmar Avatar asked Sep 30 '13 20:09

Govind Parmar


People also ask

How is printf different from cout?

The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf(). As pointed out above, printf is a function, cout an object.

Why is cout faster than printf?

Depending on what you print, either may be faster. printf() has to parse the "format" string and act upon it, which adds a cost. cout has a more complex inheritance hierarchy and passes around objects. In practice, the difference shouldn't matter for all but the weirdest cases.

Is std :: cout faster than printf?

@rashedcs printf is definitely faster than cout because of internal syncing / flushing in iostream i/o which normally slows down their performance. However using iostream with sync_with_stdio(false) makes i/o operations comparable to scanf/printf.

Is cout the same as print in Python?

cout is used in C++ to display whatever you want when print is used in python for the same purpose. Every programming language has different method for this for ex; Java ==> System.


1 Answers

The expression 18/4+18%4 evaluates to an int, and you are requesting a float. You should always compile with warnings enabled, and pay attention to them (they say a warning is a bug waiting to happen, and they are right).

This is what my compiler (GCC 4.8.1) tells me (and even without enforcing -Wall):

warning: format ‘%.5f’ expects type ‘double’, but argument 2 has type ‘int’ 

On the other hand, the std::cout<< operation is able to deduce the type of your expression and correctly stream it to your screen.

like image 184
Escualo Avatar answered Oct 12 '22 09:10

Escualo