InsaneCoder
InsaneCoder

Reputation: 8268

Understanding type conversions in C while printing values

I have read about type-casting in C, including implicit, explicit typecasting as well as integer promotion.

But what's happening in the following statement,

printf("%ld\n", 10000*10000);

I get the output as 100000000.

Can the format specifier %ld also cause type-casting or the behaviour is undefined? I was expecting to get some garbage value (loop-over from max value) as max value of int is +32767.

And whatever happens in the above statement, doesn't happen for the following statement,

printf("%f\n", 5/2); //probably 5 is double ?? If yes, how's the result justified

The output is : -0.109126. Why?

Upvotes: 3

Views: 70

Answers (4)

dbush
dbush

Reputation: 223689

In the first case:

printf("%ld\n", 10000*10000);

The literal 10000 is an int. On most systems, int is at least 32-bit. So 10000*10000 evaluates to 100000000, also an int. printf however it looking for a long int. So this is undefined behavior, regardless of the fact that you got the expected result.

In this case:

printf("%f\n", 5/2);

The literals 5 and 2 are of type int, so integer division is performed and the resulting value 2 is also of type int. printf then attempts to read this int value as a float, resulting in undefined behavior.

Upvotes: 3

chux
chux

Reputation: 153338

  1. printf("%ld\n", 10000*10000); is UB as "%ld" expects to match a long and 10000*10000 is not a long, but an int.

  2. "Can the format specifier %ld also cause type-casting" --> No

  3. "Can the format specifier %ld also cause behavior is undefined?" With few exceptions (*), the specifier and argument must match in type. Recall arguments in a variadic function go through usual promotions like short to int.

  4. The minimum value of INT_MAX is 32767. It is often 2147483647.

  5. printf("%f\n", 5/2); is UB as "%f" expects a double and 5/2 is an int.

(*) Somewhere, I think there is exception for "%d" to match unsigned and "%x" to match int. But cannot find it for verification.

Upvotes: 0

V. Michel
V. Michel

Reputation: 1619

To have your max value of int just do :

#include<stdio.h>
#include <limits.h>
main()
{
  printf("The maximum value of INT = %d\n", INT_MAX);
}

Result for me :

The maximum value of INT = 2147483647

Upvotes: 1

ameyCU
ameyCU

Reputation: 16607

printf("%f\n", 5/2); 

5/2 result is 2(an int) .It is read using %f , thus invoking UB .

If you want correct result try this -

printf("%f\n", (double)5/2); 

Upvotes: 1

Related Questions