T
Thomas Matthews
Christopher said:Given the following:
char s[15]="Hello, world\n!";
Are all the following guaranteed to produce the same output?
printf( "%s", s );
fprintf( stdout, "%s", s );
fwrite( s, sizeof(char), sizeof(s)/sizeof(char) - 1, stdout );
(It's the last of these that I'm specifically wondering about.)
In my own experience, I try to use fwrite for text that
doesn't require formatting. The printf family has an overhead
of parsing the format specifier string and handling a variable
number of arguments. In all the compilers that I've used the
printf family also brings in a whole bunch of code that may
not be necessary. If you have a simple program:
/* 1 */
int main(void)
{
printf("hello\n");
return 0;
}
I have found that the printf instruction causes the
floating point library to be hauled in. Build an
executable for the above program and compare with:
/* 2 */
int main(void)
{
puts("hello"); /* Did you forget about this one? */
return 0;
}
/* 3 */
const char * const hello_txt[] = "hello\n";
int main(void)
{
fwrite(hello_txt,
1,
sizeof(hello_txt) / sizeof(char) - 1,
stdout);
return 0;
}
They all should have identical behavior, but execution
speeds and sizes will differ.
I have tested this with:
Borland Compilers (Turbo C to 6.0)
Microsoft Compilers
Gnu
Metaware High C/C++
GreenHills
Solaris
Arm Compiler
All of these show that the execution sizes and
speeds will differ.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book