Dive Deep into CPP : cout vs printf

printf supports the display of many arguments in a single statement. It can be used properly  in only one way. But can be misused in many ways.

printf(“%d”,i,j) ;
printf(“%d%d”,i);

Here in the first statement, the value of I and j are pushed into the stack. But only one is printed. The another value that is stored in the stack will be printed along with the other argument passed in the second statement.
Also printf will display anything in the given format defined by format specifier. This is where printf fails miserably.

printf(“%s”,i) ;

Here the I is of integer type. But using printf we can print in any type we want.
So printf comes with only one advantage (i.e can print many arguments in a single statement), but has many disadvantages or loop holes. So in CPP, they designed a funtion with the advantages of printf and avoiding the misuses of printf (i.e. cout).

cout << i << j ;

This function overloads the operator << to print. This statement can be expanded like this,

cout.operator<<(I).operator<<(j);

The function specification is like

&ostream operator << (&ostream, <datavariable> );

It returns the reference object of its own class.So that it can be used in the same statement to print many arguments. The above statement is executed like,

(cout.operator<<(I)).operator<<(j);

This concept is called as cascading.Using this concept,cout is able to print many arguments.cout accepts only predefined type of arguments, i.e we can print only inbuilt datatypes using this.If you want to print someother arguments like a member of class if you pass the object of the class, you can do that by overloading the operator << to print. If you want to print the private variables of the class then make the overloaded function as a friend funtion of the class. Similarly, you can overload the operator << to print anything that are not specified in the inbuilt library. Also cout doesnt pushes the values in the stack to print, so it eliminates the misusage of values. Finally, cout is faster than printf.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s