Krrish Raj
Krrish Raj

Reputation: 1535

Unsigned int representation

 main() {

       unsigned int a=-9;
       printf("%d",a);//gives output -9


       cout<<a;// gives output 9429967287
       getch();

   }

Why it gives different output in both cases?

Do 'printf' and 'cout' treat bit pattern in a different way?

Why is 'printf' not giving the positive answer?

Upvotes: 2

Views: 468

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

If you would use format specifier %u in printf you would get the same result as for the operator <<. Specifier %d in printf forces printf to interpret the corresponding argument as having type int instead of unsigned int.

In fact it is the same if you would write

unsigned int x = -1;
std::cout << x << std::endl;
std::cout << -1 << std::endl;

Upvotes: 4

Jongware
Jongware

Reputation: 22478

Because you told it to: %d is for printing an argument as a signed int. To print an unsigned int, you should have used %u.

Upvotes: 12

Brian Bi
Brian Bi

Reputation: 119467

The %d format specifier to printf indicates that the argument is an int, not an unsigned int. So printf thinks a is an int, which is why it prints out a negative value.

Upvotes: 6

Related Questions