Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing a float to printf undefined behavior?

Tags:

c

printf

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?

like image 632
user4364319 Avatar asked Dec 26 '22 01:12

user4364319


2 Answers

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.

like image 149
Jerry Coffin Avatar answered Dec 28 '22 07:12

Jerry Coffin


float in vararg functions are always promoted to double.

scanf deals with pointers.

like image 26
lhf Avatar answered Dec 28 '22 07:12

lhf