user4364319
user4364319

Reputation: 43

Is passing a float to printf undefined behavior?

The C99 standard talks about doubles in the specification for fprintf (which subsequently applies to printf). It says "a double argument representing a floating-point number is converted..." Then in paragraph 9, it says:

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding specification, the behavior is undefined.

So I would expect the following to be undefined behavior but my compiler doesn't warn about it.

double d = 2.0;
float f = 2.0f;
printf("%f", d);
printf("%f", f); // here

On the other hand, the specification for fscanf says "floating point number" instead of double. Is it undefined behavior like this user claims?

Upvotes: 4

Views: 429

Answers (2)

lhf
lhf

Reputation: 72312

float in vararg functions are always promoted to double.

scanf deals with pointers.

Upvotes: 5

Jerry Coffin
Jerry Coffin

Reputation: 490108

Passing a float to printf is not undefined behavior--it's simply an impossibility. The float will be promoted to double before printf receives it.

scanf is different because what you're (at least normally) passing to scanf are pointers rather than the data objects themselves. Since you're passing a pointer to the original data, with scanf you need to distinguish between a float and a double.

Upvotes: 6

Related Questions