• C

For Jhandby

Your point for the comment in "simple printf question".
anikAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
JHandbyConnect With a Mentor Commented:
Here's that comment/answer again. Thanks for the points.


------------------8<---------------


Anik,


The reason that the compiler can't convert the float to an int automatically is to do with the fact that printf is declared to take a variable number of arguments. If you look in stdio.h, you'll probably see printf declared something like this:

int printf(const char *, ...);

The first argument, of type const char *, is the printf format string. This means that the compiler will be able to check the type of the first argument at compile time. The "..." indicates to the compiler that there will be zero or more arguments supplied, but that the compiler cannot make any assumptions about how many there will be, or what type they will be. This makes sense, if you think about how printf gets used:

printf("Just a string");
printf("%d green bottles", num_bottles);
printf("%d / %d = %lf", num, denom, (double)num / denom);

These are all valid printf calls (at least I hope they are :-) ), with different numbers and types of arguments. There's no way that could be type-checked or automatically converted at compile-time.

Because the compiler doesn't know how many arguments there'll be, the printf function itself is responsible for getting hold of the arguments passed to it at runtime (which is basically done internally by getting a pointer to the first argument, and moving it through memory to point to each extra argument in turn). The only information available to printf to tell it what type the arguments are and how many there should be is what you supply in your format string. So, if you tell printf to expect an int (by using "%d" in your format string), then it will try to get hold of the next argument and pull it out as an int. If you've actually passed in a float, there'll be trouble...

It's possible to create all sorts of fantastic bugs by using printf wrong :-)

For more information on variable-argument functions, look at  stdarg.h or varargs.h, depending on what flavour of compiler you're using.



Hope this helps



Jason


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.