# How Stuff Works: printf()

This topic is 4276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 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 on other sites
Quote:
 Original post by ToohrVykfloat 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 on other sites
Quote:
 Original post by willisWhat 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.

• 11
• 19
• 12
• 34
• 9
• ### Forum Statistics

• Total Topics
631398
• Total Posts
2999838
×