-2

MyCode

#include<stdio.h>
int main(){
  printf("result1 : %lf %d\n", (1 - (double)((int)1)), (1 - (double)((int)1)));
  return 1;
}

Result

result1 : 0.000000, 1

I dont't understand this result.

I think when printf("%d"), this result must be zero!

최우영
  • 33
  • 2

2 Answers2

2

Refer to the printf reference to find that the "%d" format specifier expects an int as parameter. Yet, you pass it a double. This is undefined behavior, meaning anything can happen, including the result you get (for more details on what's likely happening, refer to eg. What happens to a float variable when %d is used in a printf?).

Instead, try adding a cast to int :

printf("result1 : %lf %d\n", (1 - (double)((int)1)), (int) (1 - (double)((int)1)));
Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
  • Good explanation, you could also add why the second result is casted as double and not as Integer in the OP`s question – Alan Aug 29 '18 at 06:53
  • @Alan : I'm unsure what you mean. The third parameter *is* a `double` (due to the [usual arithmetic conversions](https://en.cppreference.com/w/c/language/conversion)), just like the second parameter (it is the same expression after all). – Sander De Dycker Aug 29 '18 at 07:09
  • My question was, as you cast the second result to (double) (int) what`s the precedence, why does It get casted double and not int – Alan Aug 29 '18 at 07:11
  • @Alan : you should really ask your own question for that, but simply put : [type casts are right-to-left associative](https://en.cppreference.com/w/c/language/operator_precedence) – Sander De Dycker Aug 29 '18 at 07:15
  • Got it thanks Sander! – Alan Aug 29 '18 at 07:19
1

The type of the arguments passed to printf have nothing inherently to do with the format string. It is your responsibility to make sure the types match up. In this case, you are passing two double values. However, the format string is attempting to interpret the second one as an integer. This is undefined behavior.

While the behavior is undefined in the general case, it is likely that you are seeing the sign bit of the IEEE 754 double in a little-endian interpretation of an integer.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264