Sign in to follow this  
willis

How Stuff Works: printf()

Recommended Posts

I must have a misunderstanding of how printf() and variable arguments work. I thought that when you write something like: printf("%d %h %f %lf\n", int_val, short_val, float_val, double_val); then the printf() function would simply read the format string to determine the size of each argument. There must be additional info that it has. Let me just write some pseudo code to explain how I thought it might work:
void *p = // point to first variable on the stack;
while (hasAnotherVariable(formatString))
{
  string variableFormat = getNextFormat(formatString); // return %d first
  size_t numBytes = getFormatSize(variableFormat);

  // cast 'p' to the appropriate type and print

  p += numBytes;
}
I must be wrong because if I use %f, printf() knows whether I really added a float or a double value to the variable argument list. I figured I would have to use %lf for double. Example, this prints the correct values for floats and doubles... why/how? printf("%f %f %lf", float_val, double_val, double_val);

Share this post


Link to post
Share on other sites
float is a narrow type, which gets promoted to double before argument passing. All float arguments to printf are, in fact, passed as double.

The same occurs for char, which gets promoted to a wide integral type.

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
float is a narrow type, which gets promoted to double before argument passing. All float arguments to printf are, in fact, passed as double.

The same occurs for char, which gets promoted to a wide integral type.


What about %llf (long double). That is larger than a normal double. If floats get promoted to doubles, why do we have %f and %lf? There are also different sized integer values that can be passed (short, int, long long), are they all promoted to a same size integer?

Share this post


Link to post
Share on other sites
Quote:
Original post by willis
What about %llf (long double). That is larger than a normal double. If floats get promoted to doubles, why do we have %f and %lf? There are also different sized integer values that can be passed (short, int, long long), are they all promoted to a same size integer?
All integer types get converted to an integer, I belive - I don't know about long longs and long doubles. I know that long long and long double are the same as long and double on MSVC, however, so I can't test it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this