Regarding C and C++ (64)

21 Name: #!/usr/bin/anonymous : 2008-05-09 00:29 ID:Heaven

>>20
How is getchar() and putchar() different from scanf() and printf()? I
heard the latter consumes more time and power because it parses the
variables, while getchar() and putchar() work with any type, whether it
is an integer or a char.

Ah, such question asks for a really long reply. I'm not up for it as my fingers
hurt, however I will briefly answer.

First of all, the C standards do not mention how long a function should take. So
the implementation is free to make getchar() faster than printf(). Anyone who
would tell you that getchar() is faster than printf() has obviously never done
any low-level or kernel work; Or any real programming anyway. I don't mean to
insult or degrade your friend thought; Perhaps you misinterpreted what he had to
say, or maybe his expertise is not C and programming in general. Anyway, my
point is that the bottleneck of both getchar() and printf() is not
`parsing' the format string; It's locking the stream, it's calling the system
call, it's switching from usermode to kernel, it's writing to the disk (when
that is done). However there are certain optimizations such as buffering that's
done from all the printf(), fprintf() etc functions. (man 3 setvbuf) so it
doesn't have to switch to kernel, it doesn't have to do the system call, it
doesn't have to actually write anything to the disk (the system call itself
doesn't have to anyway). printf("%c", 'A') and putchar('A') could differ by
10.000 instructions and you couldn't be able to tell a difference on a modern
PC. You are also not aware of the bigger picture, nor all the optimizations that
the implementation might employ. So my suggestion to you is not to worry about
the function speed in standard C, but rather, if you have to worry about
efficiency, worry about the efficiency of your own functions, and be
reasonable: whether you use 'short' or 'int' won't make a difference, unless you
are coding on a micro-processor which you are not anyway. Just try to write
clear code, and don't worry about efficiency. Learn C, then learn about
algorithm complexity.

As for the last thing you said, getchar() does not work with any type. That
doesn't even make sense. the prototype for getchar is:
int getchar(void)
The description is that getchar returns the next byte read from stdin or EOF on
error or end of file. It doesn't have to do anything with types;
Moreover, char is an integer; char is not int, but char is an integer. short,
int, long are also integers. float and double are floating-point types. Get it?

This thread has been closed. You cannot post in this thread any longer.