简体   繁体   中英

printf in gcc wrong result

Case 1: printf("%f",(7/2)); in gcc output is 0.000000.

Case 2: float k= 7/2; printf("%f",k); in gcc output is 3.000000.

In the first case printf expects float but gets Integer so gives wrong result. But in second case it does type conversion.

Here are my questions-

  1. Why does not gcc give type mismatch error/ warning in the first case?
  2. In 2nd case it is doing type conversion by default but why not in 1st case?

In 2nd case it is doing type conversion by default but why not in 1st case?

In first case 7 and 2 both are of int type. Dividing 7 by 2 will give you an int . Printing it with %f will invoke undefined behavior . You will get anything. In this case there is no type conversion.

Try this

printf("f", (7.0/2));  

In second case k is of float type hence the result of 7/2 is converted to the type of k by default.

Why does not gcc give type mismatch error/ warning in the first case?

Compiling the first statement with -Wall flag is giving the warning:

[Warning] format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]

1) gcc does not by default check types in format string with arguments - so it "interpretes" the data (ie. the integer) as float at runtime

2) gcc now interpretes the float as float at runtime .

GCC can give a warning, but you didn't enable it. Try compile with flag -Wall , you would see:

warning: double format, different type arg (arg 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM