Articles

Default argument types in C

In Uncategorized on August 31, 2009 by Matt Giuca

A thing I did not know: When you call a function in C without a prototype or with unknown arguments (for example, printf), all arguments are “promoted” to a bigger size.

Anything smaller than an int (bool, char or short) gets promoted to an int. A float gets promoted to a double. This means on a standard 32-bit machine, all variadic arguments are either 32 or 64 bits.

This explains something I’ve always wondered, which is why in printf, %f formats doubles, not floats, and %lf is the same as %f — there is no way to actually pass a float to printf, only a double. It’s different with scanf, where %f writes to a float*, and %lf writes to a double*.

Source: C language standard (ISO/IEC 9899:1999), section 6.5.2.2: Function calls, item 6:

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: