By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,796 Members | 1,168 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,796 IT Pros & Developers. It's quick & easy.

puts() vs printf()

P: n/a
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters. I'm not very
good at modern-day assembly, so I can't compare it that way.
I've generally steered away from the puts-gets I/O functions in the
past. I don't know why this is the case...maybe it has to do with
consistency as I don't always want the newline automatically output.

What's the word?

Thanks.

p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
Aug 24 '06 #1
Share this Question
Share on Google+
36 Replies


P: n/a
In article <hk********************************@4ax.com>,
Debaser <x@x.comwrote:
>I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:
>puts("Some random text");
>vs.
>printf("Some random text\n");
>[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation.
printf() -likely- calls va_init() unconditionally, but after that
there would be no arguments to process as there are no format
elements. Calling or not calling va_init() would be a constant time
factor, probably nearly undetectable.

printf() must examine each character at least once in order to
figure out that it is -not- a format character. If it is using
putc() to output characters, then in theory it could just output
each character immediately. It needs to test each character to
see if it is \0 anyhow, but two comparisons per character
instead of one might detectable on long enough strings.

If printf() is implimented by printing the entire string into a buffer
first, such as by calling sprintf() and then outputing the resulting
string, then the overhead of doing that would likely be detectable.

If you think about it, you will see that there is effectively
no way for printf() to do -less- work than puts() does: if there
were then puts() would use that method instead. The questions then
becomes one of QOI (Quality of Implementation), together with
a question about instruction set architecture. In theory, two
tests per loop is not *necessarily* any slower than one, as there
could be an instruction that was effectively "move string until
delimeter", or the two tests might be overlapped, or the tight
loop could be micro-optimized. (The instruction set visible to
the programming level is often not the instruction set used
internally: microcoding is quite common.)
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
Aug 24 '06 #2

P: n/a
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters. I'm not very
good at modern-day assembly, so I can't compare it that way.
I've generally steered away from the puts-gets I/O functions in the
past. I don't know why this is the case...maybe it has to do with
consistency as I don't always want the newline automatically output.
puts(str) is usually faster than printf(str) because it
doesn't need to search through `str' for conversion specifications
like "%d". (Note that if `str' contains anything that looks
even vaguely like a conversion specification, printf(str) will
be in deep trouble -- printf("category\tcount\t%frequency\n")
is most definitely a no-no.)

That said, the difference is likely to be so small that it's
unnoticeable, probably even so small that it will be difficult
to measure. Consider: You've got actual data output operations
going on, in order to deliver the printf()/puts() characters to
their destination -- disk file, pipe, cable modem with WhizFiber,
or whatever. All of these channels are VASTLY slower than the
CPU that executes the function call; by switching to the "more
efficient" variety you may be doing nothing more than increasing
the iteration count of the idle loop.

A friend of mine once described this sort of optimization as
"Cleaning the bottle tops off the beach so the sand will be nice
and clean around the beached whale carcases." Ponder that.
p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
I, personally, have never read any of Herr Schildt's works.
Others have, and have commented on them more perspicaciously than
I could; see, for example,

http://www.lysator.liu.se/c/schildt.html

It has been observed that Schildt's "The Annotated C Standard"
costs less than the Standard itself, and it has been opined that
the difference in price reflects the value of the annotations.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 24 '06 #3

P: n/a
On Wed, 23 Aug 2006 20:23:20 -0400, Debaser <x@x.comwrote:
>I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
It is strictly a quality of implementation issue. I personally
believe the assertion is generally true but that and a quarter still
won't buy you a cup of coffee.
>printf() uses vargs, but I'd like some confirmation. The author uses
Not because of variable arguments but because puts is a single minded
function (send an already formatted string to stdout) while printf has
so many bells and whistles that it "should" take more time to figure
out what it is you really want to do is the same.

It is also possible that some clever library writer decided this
degenerative use of printf is so common that a special check is made
early in the code and therefore the difference is immeasurably small.
>void main() so I'm not sure what to think. Given today's hardware and
A lot of books do unfortunately but it still serves as a reminder that
the author is prone to carelessness.
>compiler optimizations I have no idea if it even matters. I'm not very
good at modern-day assembly, so I can't compare it that way.
I've generally steered away from the puts-gets I/O functions in the
past. I don't know why this is the case...maybe it has to do with
consistency as I don't always want the newline automatically output.

What's the word?

Thanks.

p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
Be afraid, be very afraid!
Remove del for email
Aug 24 '06 #4

P: n/a
Debaser wrote:
>
I've recently read in one of my old C books that puts() is a
better function call with regard to performance than printf()
in the following situation:

puts("Some random text");
vs.
printf("Some random text\n");
.... snip ...
>
p.s. The book is by Herb Schlidt (or something similar) if
that's any indication.
It is. BullSchildt is normally error infested. In this particular
case he is right. This is analagous to undefined behaviour -
sometimes you get the expected result.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 24 '06 #5

P: n/a
On Wed, 23 Aug 2006 21:33:08 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrote:
[snip]
>It has been observed that Schildt's "The Annotated C Standard"
costs less than the Standard itself, and it has been opined that
the difference in price reflects the value of the annotations.
It's actually "The Annotated ANSI C Standard", ISBN 0-07-881952-0.

It has the text of the ANSI/ISO 9899-1990 standard on the left-hand
pages and Herbert's comments on the right-hand pages.

Unless I'm in need of a good laugh, I close my right eye when reading
this book. Both eyes open or not, it makes for real good reading--well
worth the price--providing you can find it.

It's unfortunate that someone like Steve Summit didn't write this
book.

Regards
--
jay
Aug 24 '06 #6

P: n/a
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters. I'm not very
good at modern-day assembly, so I can't compare it that way.
I've generally steered away from the puts-gets I/O functions in the
past. I don't know why this is the case...maybe it has to do with
consistency as I don't always want the newline automatically output.

What's the word?

Thanks.

p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
When in doubt of relative speed of alternatives, you could put both
solutions to the test. A longer test run probably is more accurate than
a single loop.

#define RUNS 1000000UL
int main (void)
{
unsigned long i;
for (i=0;i<RUNS;i++) {
printf("stuff\n");
// puts("stuff"); alternate with printf.
}
return 0;
}

Then compile and run the program. If your OS has no standard timer you
could use a built-in timer in the program, or time manually (but then
you really want long runs for reliability/accuracy). *nix offers you the
command time which shows you user, system and real time used by the
program. Simply recompile with the different options enabled and go.
>$ time ./a.out
should do the trick, where a.out is the default binary file name created
by gcc. Output-related measurements are more accurate/reliable when the
output is redirected to the bitbucket.

I just ran this example on my own system:

1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

time ( ./a.out &/dev/null ) // printf(), 100 char string
real 0m4.174s
user 0m4.128s
sys 0m0.042s

time ( ./a.out &/dev/null ) // puts(), 100 char string
real 0m1.484s
user 0m1.443s
sys 0m0.036s

I wonder how often one has to output a gazillion const strings making
the difference relevant though...

Rgds
Sh
Aug 24 '06 #7

P: n/a

Schraalhans Keukenmeester wrote:
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");
vs.
printf("Some random text\n");

When in doubt of relative speed of alternatives, you could put both
solutions to the test.
[snip]
1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

I wonder how often one has to output a gazillion const strings making
the difference relevant though...
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.

Aug 24 '06 #8

P: n/a
jaapsch wrote:
Schraalhans Keukenmeester wrote:
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:
>
puts("Some random text");
vs.
printf("Some random text\n");
When in doubt of relative speed of alternatives, you could put both
solutions to the test.
[snip]
1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

I wonder how often one has to output a gazillion const strings making
the difference relevant though...

I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.
Actually, gcc does do just that for string literals that end with a
newline and don't contain %.

Robert Gamble

Aug 24 '06 #9

P: n/a
jaapsch wrote:
>
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.
Compiler writers obey strange masters.

A former colleague who had labored as a compiler writer
for a large computer company (now defunct) told me he *did*
put this transformation into their compiler. Why? Because
parts of the SPEC benchmark suite used many "non-converting"
printf() calls, and by switching to puts() they raised their
SPEC scores without the silly bother of needing to make the
machine any faster. The improvement was only a milliwhisker
or two, but a computer maker will jump through a lot of hoops
for the appearance of greater speed ("As measured on industry-
standard benchmarks!").

Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 24 '06 #10

P: n/a
Eric Sosman wrote:
>
.... snip ...
>
A former colleague who had labored as a compiler writer
for a large computer company (now defunct) told me he *did*
put this transformation into their compiler. Why? Because
parts of the SPEC benchmark suite used many "non-converting"
printf() calls, and by switching to puts() they raised their
SPEC scores without the silly bother of needing to make the
machine any faster. The improvement was only a milliwhisker
or two, but a computer maker will jump through a lot of hoops
for the appearance of greater speed ("As measured on industry-
standard benchmarks!").
Yet it did make that system faster in general. It also probably
reduced the object size of some fraction of programs. The fact
that its effects were exagerrated by the benchmark is just a bonus
:-)

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 24 '06 #11

P: n/a
"Debaser" <x@x.comwrote in message
news:hk********************************@4ax.com...
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters.
A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I don't
have to deal with forgetting the implicit '\n' that puts() adds.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 24 '06 #12

P: n/a
Eric Sosman wrote:
jaapsch wrote:
>>
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.

Compiler writers obey strange masters.
<snip optimising printf to puts>
Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.
In my opinion it is not a completely silly optimisation to do, it is
just one more example of strength reduction, although not necessarily
one that is high priority to implement. However, if it has a noticeable
effect on benchmark results then the benchmark is possibly not as good
as it should be.
--
Flash Gordon
Aug 24 '06 #13

P: n/a
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

I would use puts() in this case, just because it's the routine made for
that operation. Less typing too. With no conversions to perform, I'd
only use printf() if I didn't want an automatic newline.


Brian (clarity not speed is the determing factor)
Aug 24 '06 #14

P: n/a
Stephen Sprunk wrote:
"Debaser" <x@x.comwrote in message
news:hk********************************@4ax.com...
>I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters.

A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I don't
have to deal with forgetting the implicit '\n' that puts() adds.

S
Slightly wandering OT: Tried my example (see my other response in this
thread) with gcc optimization enabled and ONLY when the string is a
literal or a #defined constant it looks as if execution times are
identical, which may be (and probably is) indicative of printf() being
replaced by the faster puts(). Declaring the string (even as const)
*char does not convince gcc to use puts() in stead of printf(), at least
not here.

Would you say that gcc is a modern or old compiler based on this?
Sh.
Aug 24 '06 #15

P: n/a
Robert Gamble wrote:
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.

Actually, gcc does do just that for string literals that end with a
newline and don't contain %.
gcc also changes 'printf("%s\n", str)' into 'puts(str)'.

$ gcc -S -O2 -x c - -o -
#include <stdio.h>
extern char *p;
int main(void) { printf("%s\n", p); return 0; }
^D .file ""
.text
.p2align 2,,3
..globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
subl $28, %esp
pushl p
call puts
xorl %eax, %eax
leave
ret
.size main, .-main
.ident "GCC: (GNU) 3.4.4 [FreeBSD] 20050518"

Aug 24 '06 #16

P: n/a
"Schraalhans Keukenmeester" <fi********************@xsfourall.ennel>
wrote in message news:44**********************@news.xs4all.nl...
Stephen Sprunk wrote:
>A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I
don't
have to deal with forgetting the implicit '\n' that puts() adds.

Slightly wandering OT: Tried my example (see my other response in this
thread) with gcc optimization enabled and ONLY when the string is a
literal or a #defined constant it looks as if execution times are
identical, which may be (and probably is) indicative of printf() being
replaced by the faster puts(). Declaring the string (even as const)
*char does not convince gcc to use puts() in stead of printf(), at
least
not here.

Would you say that gcc is a modern or old compiler based on this?
Sh.
My experience plus Racaille's report in another post lead me to say it's
modern, i.e. doing something reasonably clever as I described. It's
curious that it doesn't convert a printf(char*) to puts(char*) but does
with literals, but there may be some reason for that or it might be a
bug (at least in your version).

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 24 '06 #17

P: n/a
Flash Gordon wrote:
>
.... snip ...
>
<snip optimising printf to puts>
Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.

In my opinion it is not a completely silly optimisation to do, it
is just one more example of strength reduction, although not
necessarily one that is high priority to implement. However, if
it has a noticeable effect on benchmark results then the
benchmark is possibly not as good as it should be.
If that optimization manages to remove ALL references to printf,
then there is no need to load all that monstrous output
interpreter, and there can be significant reduction in the size of
the output code.

Fighting bloat at every turn :-)

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 24 '06 #18

P: n/a
Stephen Sprunk wrote:
>
.... snip ...
>
My experience plus Racaille's report in another post lead me to
say it's modern, i.e. doing something reasonably clever as I
described. It's curious that it doesn't convert a printf(char*)
to puts(char*) but does with literals, but there may be some
reason for that or it might be a bug (at least in your version).
It can't. The output of the two statements is different.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 25 '06 #19

P: n/a

jaysome wrote:
On Wed, 23 Aug 2006 21:33:08 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrote:
[snip]
It has been observed that Schildt's "The Annotated C Standard"
costs less than the Standard itself, and it has been opined that
the difference in price reflects the value of the annotations.

That and the fact that the middle of 7.6.9.1 is omitted because the
preceding page is duplicated.

Aug 25 '06 #20

P: n/a
Stephen Sprunk wrote:
A modern compiler will notice when a single argument to printf()
contains no format specifiers
I think that would bother me because I consider the compiler knowing
this much about a parameter to a library function to be pathological
binding. I realize it's a very standard library function with
well-defined parameters, but still, this feels like a violation of some
boundary that shouldn't be crossed. What a nasty surprise if someone
implements his own standard IO library and discovers the compiler has
different ideas about format strings?
Aug 25 '06 #21

P: n/a
jmcgill wrote:
Stephen Sprunk wrote:
>A modern compiler will notice when a single argument to printf()
contains no format specifiers

I think that would bother me because I consider the compiler knowing
this much about a parameter to a library function to be pathological
binding. I realize it's a very standard library function with
well-defined parameters, but still, this feels like a violation of some
boundary that shouldn't be crossed. What a nasty surprise if someone
implements his own standard IO library and discovers the compiler has
different ideas about format strings?
Doing so at the user level is expressly forbidden by the standard.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 25 '06 #22

P: n/a
CBFalconer wrote:
jmcgill wrote:
>Stephen Sprunk wrote:
>>A modern compiler will notice when a single argument to printf()
contains no format specifiers
I think that would bother me because I consider the compiler knowing
this much about a parameter to a library function to be pathological
binding. I realize it's a very standard library function with
well-defined parameters, but still, this feels like a violation of some
boundary that shouldn't be crossed. What a nasty surprise if someone
implements his own standard IO library and discovers the compiler has
different ideas about format strings?

Doing so at the user level is expressly forbidden by the standard.

Fair enough. But still would not appreciate the idea of the compiler
snooping into my function arguments and deciding for me if they are needed.

Does GCC do this?
Aug 25 '06 #23

P: n/a
jmcgill <jm*****@email.arizona.eduwrites:
CBFalconer wrote:
>jmcgill wrote:
>>Stephen Sprunk wrote:

A modern compiler will notice when a single argument to printf()
contains no format specifiers
I think that would bother me because I consider the compiler knowing
this much about a parameter to a library function to be pathological
binding. I realize it's a very standard library function with
well-defined parameters, but still, this feels like a violation of some
boundary that shouldn't be crossed. What a nasty surprise if someone
implements his own standard IO library and discovers the compiler has
different ideas about format strings?

Doing so at the user level is expressly forbidden by the standard.

Fair enough. But still would not appreciate the idea of the compiler
snooping into my function arguments and deciding for me if they are needed.

Does GCC do this?
1) Yes it does, but that's off-topic.
2) Your compiler needs to see your paramaters in order to compile. Unless
you're hiding drugs in them, there's no reason for you not to want the
compiler searching them.

--
Andrew Poelstra <http://www.wpsoftware.net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Aug 25 '06 #24

P: n/a
Andrew Poelstra wrote:
>Fair enough. But still would not appreciate the idea of the compiler
snooping into my function arguments and deciding for me if they are needed.

Does GCC do this?

1) Yes it does, but that's off-topic.
I figured.
2) Your compiler needs to see your paramaters in order to compile. Unless
you're hiding drugs in them, there's no reason for you not to want the
compiler searching them.
Still bothers me. I don't mind the preprocessor seeing this, and maybe
having it feed the compiler what it wants. But what we are talking
about here is the compiler itself evaluating string literals and making
arbitrary changes to them. It bugs me in a philosophical way, even
though I don't care in any practical sense.
Aug 25 '06 #25

P: n/a


jmcgill wrote On 08/25/06 11:12,:
[... about substitution of Standard functions based on arguments ...]

Fair enough. But still would not appreciate the idea of the compiler
snooping into my function arguments and deciding for me if they are needed.
If I write pow(x,5) it does not bother me in the least if
the compiler generates a call to _intpow(x,5), a hypothetical
optimized-for-integer-powers version.

If I write strlen("Hello, world!") I am delighted if the
compiler just generates (size_t)13.

If I write memcpy(p, q, sizeof *p) I applaud the compiler
that generates a block-move instruction instead of a function
call. For div(num, den) I would be disappointed if the compiler
did *not* generate an in-line division. I *want* sqrt() to
turn into an FSQRT instruction when it can.

Why should printf() be any different?

--
Er*********@sun.com

Aug 25 '06 #26

P: n/a
CBFalconer wrote:
>
Debaser wrote:

I've recently read in one of my old C books that puts() is a
better function call with regard to performance than printf()
in the following situation:

puts("Some random text");
vs.
printf("Some random text\n");
... snip ...

p.s. The book is by Herb Schlidt (or something similar) if
that's any indication.

It is. BullSchildt is normally error infested. In this particular
case he is right. This is analagous to undefined behaviour -
sometimes you get the expected result.
And newbie folks need to understand: Undefined Behavior means
that you can get *any* result, including sometimes the result
that you expected. Just don't count on getting the result that
you expected...

--
+----------------------------------------------------------------+
| Charles and Francis Richmond richmond at plano dot net |
+----------------------------------------------------------------+
Aug 25 '06 #27

P: n/a
Charles Richmond wrote:
Undefined Behavior means
that you can get *any* result, including sometimes the result
that you expected. Just don't count on getting the result that
you expected...
Would you say that undefined behavior also entitles an implementor to
define the behavior as appropriate for a given implementation, or would
you say that undefined behavior should remain *expressly* undefined, and
should *not* be defined by any given implementation?
Aug 25 '06 #28

P: n/a


jmcgill wrote On 08/25/06 13:12,:
Charles Richmond wrote:
>>Undefined Behavior means
that you can get *any* result, including sometimes the result
that you expected. Just don't count on getting the result that
you expected...


Would you say that undefined behavior also entitles an implementor to
define the behavior as appropriate for a given implementation, or would
you say that undefined behavior should remain *expressly* undefined, and
should *not* be defined by any given implementation?
The former.

I'm having some fun trying to imagine the documentation
if the latter were true. "If the program dereferences a
NULL pointer the system *may* nudge nudge raise a signal
that *might* wink wink be called SIGSEGV, but -- say no
more, say no more, you *didn't* hear that from *me*, eh?"

--
Er*********@sun.com

Aug 25 '06 #29

P: n/a
Charles Richmond wrote:

<snip>
And newbie folks need to understand: Undefined Behavior means
that you can get *any* result, including sometimes the result
that you expected. Just don't count on getting the result that
you expected...
Don't count on not getting the result you expect either. I.e. don't
assume that just because your program gave the correct result it is
necessarily correct. It could still contain undefined behaviour and only
fail when it is most important to you that it works, for example when
you are doing a demonstration to win that multi-million pound bid.
--
Flash Gordon.
Aug 25 '06 #30

P: n/a
jmcgill wrote:
Charles Richmond wrote:
>Undefined Behavior means
that you can get *any* result, including sometimes the result
that you expected. Just don't count on getting the result that
you expected...

Would you say that undefined behavior also entitles an implementor
to define the behavior as appropriate for a given implementation,
or would you say that undefined behavior should remain *expressly*
undefined, and should *not* be defined by any given implementation?
It's undefined from the point of view of the C standard. Just
because the implementor arranges for a particular response doesn't
mean that the same will occur on another system.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Aug 25 '06 #31

P: n/a
"jmcgill" <jm*****@email.arizona.eduwrote in message
news:DQvHg.8118$cw.7613@fed1read03...
Stephen Sprunk wrote:
>A modern compiler will notice when a single argument to printf()
contains no format specifiers

I think that would bother me because I consider the compiler knowing
this much about a parameter to a library function to be pathological
binding. I realize it's a very standard library function with
well-defined parameters, but still, this feels like a violation of
some
boundary that shouldn't be crossed. What a nasty surprise if someone
implements his own standard IO library and discovers the compiler has
different ideas about format strings?
The compiler is allowed to "violate that boundary" because the standard
says so. Presumably there's some switch to turn off that optimization
if you don't like it, but why wouldn't you? It only happens in cases
it's proven to be safe, and it follows the as-if rule. There's lots of
scarier/cleverer things that compilers do these days; this is a minor
nit.

If the above offends you, so should GCC complaining if the arguments in
a call to printf() don't match the format string. How is pointing out
bugs a bad thing?

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 25 '06 #32

P: n/a
"CBFalconer" <cb********@yahoo.comwrote in message
news:44***************@yahoo.com...
Stephen Sprunk wrote:
>My experience plus Racaille's report in another post lead me to
say it's modern, i.e. doing something reasonably clever as I
described. It's curious that it doesn't convert a printf(char*)
to puts(char*) but does with literals, but there may be some
reason for that or it might be a bug (at least in your version).

It can't. The output of the two statements is different.
The compiler should be able to convert this:

char *foo = "Hello world!\n";
printf(foo);

to this:

char *foo = "Hello world!";
puts(foo);

under the as-if rule, provided there's no other use of foo's contents.
However, proving the latter point may not be worth the effort, so only
things of the form printf("Hello world!\n"); or printf("%s\n",foo);
would be converted.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 25 '06 #33

P: n/a
Stephen Sprunk wrote:
The compiler is allowed to "violate that boundary" because the standard
says so.
I buy it fine. I hadn't fully considered that we're only talking about
standard library calls in the first place.
Aug 26 '06 #34

P: n/a
CBFalconer wrote:
It's undefined from the point of view of the C standard. Just
because the implementor arranges for a particular response doesn't
mean that the same will occur on another system.

My question is more along the lines of this, and I don't think I was
clear enough:

Does an undefined behavior, that is explicitly undefined in the spec (as
opposed to the infinite things being undefined by ommission), mean that
the spec is attempting to require that behavior to be undefined, or is
it open enough that an implementation that defines some specific
behavior for that case is not nonconforming as a result?

Maybe that's still not clear enough.

Aug 26 '06 #35

P: n/a

jmcgill wrote:
Stephen Sprunk wrote:
The compiler is allowed to "violate that boundary" because the standard
says so.

I buy it fine. I hadn't fully considered that we're only talking about
standard library calls in the first place.

The copmiler is also free to do so for non-library functions, within
the bounds set by the as-if rule. So if the defintion of mystrlen() is
adequetely visible to the compiler (and assuming the obvious
implementation of that function), the compiler is free to reduce
"a=mystrlen("somestring")" to "a=9".

In fact, this sort of optimization is quite common with inlined
functions.

Aug 27 '06 #36

P: n/a
<ro***********@yahoo.comwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
>
jmcgill wrote:
>Stephen Sprunk wrote:
The compiler is allowed to "violate that boundary" because the
standard
says so.

I buy it fine. I hadn't fully considered that we're only talking
about
standard library calls in the first place.

The copmiler is also free to do so for non-library functions, within
the bounds set by the as-if rule. So if the defintion of mystrlen()
is
adequetely visible to the compiler (and assuming the obvious
implementation of that function), the compiler is free to reduce
"a=mystrlen("somestring")" to "a=9".

In fact, this sort of optimization is quite common with inlined
functions.
With inlined functions, it's fair to _assume_ your compiler will do such
optimizations; if it doesn't, it's time to upgrade. Better compilers
have "inter-procedural optimization" or "whole-program optimization",
which allow them to do the same thing with non-inline functions within
the same translation unit or even across translation units -- provided,
of course, they can prove the "as if" rule applies.

<OT>The GCC folks have recently started playing with IPO within the same
translation unit, but it's still in it infancy and only seems to work on
inline and static functions so far; many commercial compilers have had
IPO for a while. A few have WPO, but typically that means the "compile"
stage emits some intermediate representation and actual compilation and
most optimization is delayed until the "link" stage. The GCC folks
haven't made any noises they're considering that route, but five years
from now I wouldn't be surprised to see it.</OT>

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 27 '06 #37

This discussion thread is closed

Replies have been disabled for this discussion.