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);
How Stuff Works: printf()
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:
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.
The same occurs for char, which gets promoted to a wide integral type.
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?
Quote:Original post by willisAll 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.
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?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement