akash
akash

Reputation: 1801

Consider the program output

Consider the program

#include<stdio.h>
int main()
{
  int  x = 33;
  float y = 5;

  printf("%d %d",y,x);
  return 0;
}

Output:

0 1075052544

I can understand the value of y coming 0 as UB but y x is coming so? Here is an ideone sample.

Upvotes: 1

Views: 186

Answers (3)

Daniel Fischer
Daniel Fischer

Reputation: 183978

Once you have undefined behaviour, anything is allowed to happen, so you can't really expect anything sensible after printing with the wrong conversion specifier.

However, in this case, we can reconstruct what most probably happened.

printf is a variadic function, hence its arguments undergo the default argument promotions. That means float arguments are promoted to double before they are passed to printf.

The IEEE754 double representation of 5 is

0x4014000000000000

encoding a sign-bit 0, an exponent of 2 + 1023 = 1025 = 0x401 and a significand of 5/4, which, removing the hidden 1-bit becomes 0x4000000000000.

The values printed are 0 and 1075052544 = 0x40140000. They correspond to the low-order 32 bits of the double 5 and the high-order 32 bits of it, respectively.

Upvotes: 6

user2448027
user2448027

Reputation: 1638

You use incorrect formatting for y which is a float. In printf, "%d" is for integers (int) and "%f" for floating-point data (float).

This is the correct way to print x and y (provided x is int and y is float):

printf("%f %d", y, x);

As to x, it's probably (I'm not completely sure) printed incorrectly because invalid formatting is used for printing the variable before that (y).

Upvotes: 1

Cory Klein
Cory Klein

Reputation: 55860

Use %f for printing floating point numbers

printf("%f %d",y,x);

Upvotes: 1

Related Questions