Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 119,783 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 1,381 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Printf V/s Cout [DreamInCode.net]

2 Pages V  1 2 >  
Reply to this topicStart new topic

> Printf V/s Cout [DreamInCode.net], Which one is better?

Rating  3
born2c0de
Group Icon



post 28 Feb, 2005 - 04:02 AM
Post #1


printf() v/s cout....which one is better?
I just started writing this tutorial...and here's the current unfinished version showing the winner when it comes to "code generation". I'll post further updates soon as I finish writing them...

Enjoy!!!

P.S -> Please Correct Me if I am wrong in certain places....


Many people still think that printf and scanf belongs to C while cout and cin
belongs to C++ and so they avoid using printf and scanf while writing programs
in C++. Of-course you cant do this viceversa but depending on the design of your
program you should use printf and cout accordingly. This is because printf
though cryptic and complex in it's nature takes up a lot fewer bytes than what
cout hogs up. This is exactly what this article does. This Article will show you
which function is better under a certain situation. You will need a disassembler
or a debugger to carry on with this Article. IDA Pro™ and OllyDebug™ are
recommended for understanding this article. W32DASM™ can be used as well. If
you don't have a copy of these, you can contact me at born2c0de@hotmail.com
So Let's begin without wasting any time.


I. CONSTANTS AND LITERALS

Our first test is to see which function takes up the least amount of space as
far as printing out constants or literalsis concerned. Consider this following
program:
CODE
#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
   cout<<"THIS IS A LITERAL\n";
   printf("THIS IS A LITERAL\n");
   int i=10;
   cout<<i<<endl;
   printf("%d\n",i);
   return 0;
}


Here is it's Disassembled Listing generated by Interactive Disassembler 4.50 Pro:
CODE
; int __cdecl main(int argc,const char **argv,const char *envp)
_main       proc near; DATA XREF: .data:0040D0E0o

               argc       = dword ptr  8
               argv       = dword ptr  0Ch
               envp       = dword ptr  10h

.text:00401108       push    ebp
.text:00401109       mov     ebp, esp
.text:0040110B       push    ebx
;                  ----------------------------THE COUT FUNCTION STARTS HERE
.text:0040110C[2]       push    0
.text:0040110E[5]       push    offset aThisIsALiteral;"THIS IS A LITERAL\n"
.text:00401113[5]       push    offset unk_40FEDC
.text:00401118[5]       call    @ostream@outstr$qpxct1;ostream::outstr(char *,char *)
.text:0040111D[3]       add     esp, 0Ch
;                  ----------------------------THE COUT FUNCTION ENDS HERE

;                  ----------------------------PRINTF STARTS HERE
.text:00401120[5]       push    offset aThisIsALiter_0;format
.text:00401125[5]       call    _printf
.text:0040112A[1]       pop     ecx
;                  ----------------------------PRINTF ENDS HERE
.text:0040112B       mov     ebx, 0Ah
;                  ----------------------------COUT STARTS HERE
.text:00401130[2]       mov     eax, ebx
.text:00401132[1]       push    eax
.text:00401133[5]       push    offset unk_40FEDC
.text:00401138[5]       call    @ostream@$blsh$ql; ostream::operator<<(long)
.text:0040113D[3]       add     esp, 8
.text:00401140[1]       push    eax
.text:00401141[5]       call    @endl$qr7ostream; endl(ostream &)
.text:00401146[1]       pop     ecx
;                  ----------------------------COUT ENDS HERE
;                  ----------------------------PRINTF STARTS HERE
.text:00401147[1]       push    ebx
.text:00401148[5]       push    offset aD; format
.text:0040114D[5]       call    _printf
.text:00401152[3]       add     esp, 8
;                  ----------------------------PRINTF ENDS HERE
.text:00401155       pop     ebx
.text:00401156       pop     ebp
.text:00401157       retn
_main       endp
.data:0040D110 aThisIsALiteral db 'THIS IS A LITERAL',0Ah,0; DATA XREF: _main+6o
.data:0040D123 aThisIsALiter_0 db 'THIS IS A LITERAL',0Ah,0; DATA XREF: _main+18o
.data:0040D136 aD       db '%d',0Ah,0; DATA XREF: _main+40o
.data:0040FEDC unk_40FEDC      db    ?;; DATA XREF: _main+Bo


I have given the addresses as well so that you can compute how many bytes an
instruction takes up. From now on, i wont show the addresses. Instead I'll
include the space taken up as bytes in Square Brackets as I have already done
here. Let us now compare the results of both:

LITERAL OUTPUT:
cout -> 20 Bytes
printf -> 11 Bytes [ 55% of cout ]

CONSTANT OUTPUT:
cout -> 23 Bytes
printf -> 14 Bytes [ 60.86% cout ]

OVERALL: printf takes up 58.13% lesser space than cout.

This post has been edited by born2c0de: 6 Oct, 2007 - 07:26 AM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Amadeus
Group Icon



post 28 Feb, 2005 - 10:27 AM
Post #2
I'd like to point out not a mistake, but something to be considered. You are correct in stating that printf() is often the more efficient of the two, but there is something that should be noted.

printf() is a function...one designed to output formatted data to the screen. It is much faster than cout becasue cout is not a function...it is an object, one complete with many member methods and useful structures. The fact that cout is an object with these available members necessitates that it has more overhead that a function such as printf().

cout.bad(), cout.good(), cout.fail(), cout.setf(), cout.setstate(), and cout.clear() are just a few of the more than 30 members of the cout object that provide the user with enhanced functionality. To recreate this functionality with printf() would require separate functions for each corresponding member, and they would not be specifically made to work with the printf() function, but a more generic version.

All that to say that printf() is usually faster than cout, but only when used for the strict output of code to the screen. printf() and cout are apples an oranges. If all available cout functionality were recreated with printf(), I belive you might find the pendulum of efficiency swinging in the other direction.
Go to the top of the page
+Quote Post

born2c0de
Group Icon



post 1 Mar, 2005 - 12:29 AM
Post #3
agreed...i'll mention that in the article as well...Thanx Amadeus
Go to the top of the page
+Quote Post

razom
*



post 1 May, 2006 - 12:10 AM
Post #4
i think printf will be better
Go to the top of the page
+Quote Post

razom
*



post 1 May, 2006 - 12:11 AM
Post #5
in addition i think that C programming is easier than C++
Go to the top of the page
+Quote Post

William_Wilson
Group Icon



post 1 May, 2006 - 08:19 AM
Post #6
C is of course considerably easier, as there is a distinct lack of objects for the main part. This make programing much more complicated, but also MUCH more advanced.

I'm not too sure about the 2 output statements, they both rightfully have there place, but i often find myself using the added functionality of cout and for good coding practise i use only cout to print any and all text.
Go to the top of the page
+Quote Post

shikha
*



post 23 May, 2006 - 02:04 AM
Post #7
smile.gif hi...... nice n intresting topic rolleyes.gif
Go to the top of the page
+Quote Post

salindor
Group Icon



post 8 Jun, 2007 - 06:16 PM
Post #8
Personally I suggest never using scanf if you can possibly avoid it.

When I was taking a class on penetration testing, (the same type of testing hackers use to break things like windows and word), scanf is one of the first functions they attempt to attack. Invision the following code:

CODE

.
.
.
char buf[1024];
scanf("%s", buf);
printf(buf);
.
.
.


what I would try doing is something like is giving it an input stream like %s and just see what comes back. Or maybe I could have some fun and do %d.

Or lets say you get rid of the printf or you change the printf to something like
CODE
printf("%s", buf)
instaed; what I might try doing, is inputing a string that is 1026 in size and seeing how the program handles reading in the string.

Now granted I am not being fair to cin, after all if I remember right, it is still possible to overflow its buffers and I have crashed cin when I tell it to read to an int, and instead pass in a variable. I have not tried the same test against scanf because I have seen hackers attack it so successfully.

Typically what I will do, is read in a specific number of character I require instead, perform checks against the input to ensure the input is exactly as I expect it, and only if it passes my tests pass it on.

So I guess the answer is in the end, what are your goals. Are you just writting something to test, or for your teacher. Then the answer is it really doesn't matter. Are you writting something you expect the world to see, then the answer is neither.

Salindor
Go to the top of the page
+Quote Post

born2c0de
Group Icon



post 10 Jun, 2007 - 08:25 AM
Post #9
Very True Indeed.

Infact I have managed to Overflow Buffers using scanf and Heap Overflows with malloc.
However I've never tried it using cin and new.
Thanks.
Go to the top of the page
+Quote Post

no2pencil
Group Icon



post 10 Jun, 2007 - 09:06 AM
Post #10
My 2¢, I think printf code looks cleaner than cout. I always cringe when I see cout << "Text " << variable << " more Text " << another variable << function;

Bleh...
Go to the top of the page
+Quote Post

Smarf
**



post 3 Oct, 2007 - 12:41 PM
Post #11
I'd like to make a suggestion.

Could you please not post the entire tutorial inside the code tags?

On most systems the code window is smaller and needs to be scrolled left and right to read all the text. The scroll bars however are at the very bottom of the article, making it very difficult to read.

Something like this:

Table of Contents:

1: Blah
2: Blah

Section 1:
C++ is great, check out this code.

CODE
cout << "Hello World!";


Section 2:
VB stinks, check out this code.

CODE
Console.WriteLine("Look at me, I don't need semi colons")
Go to the top of the page
+Quote Post

born2c0de
Group Icon



post 5 Oct, 2007 - 02:32 AM
Post #12
Done.
Thanks.
Go to the top of the page
+Quote Post


2 Pages V  1 2 >
Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 10/15/08 09:45PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month