-3

When I printed value of b using two of ways, I though it should be the same output on the console, but it didn't.

unsigned int b = -1000;
std::cout << b << std::endl;
printf("%d\n",b);

Output:

cout: 4294966296
printf: -1000

The correct value of b should be around 0 -> 4294967296. The output of cout is correctly. However, I did not understand why the printf keeping wrong value?

Can anyone explain to me ?

Adam Duong
  • 95
  • 1
  • 7
  • you're printing `unsigned int` with `%d` which invokes undefined behavior. In most implementations it'll simply treat the bit patterns in the unsigned as signed – phuclv Jun 24 '17 at 05:54
  • https://stackoverflow.com/questions/16864552/what-happens-when-i-use-the-wrong-format-specifier It's not same my issue. It's talking about wrong format specifier it was not explained why cout and printf have different output. – Adam Duong Jun 24 '17 at 05:56
  • 1
    cout is using the correct type of the variable so obviously it'll print an unsigned value] – phuclv Jun 24 '17 at 05:57
  • Thank Phuc. I understood now, just because I was using wrong format specifier. – Adam Duong Jun 24 '17 at 06:00

2 Answers2

2

You're telling printf to print a signed int value with the %d format specifier. Technically undefined behavior, but most implementations will convert the unsigned value back to the equivalent signed value to print.

You want %u to print an unsigned value.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
1

printf("%d\n",b); prints a signed number due to the %d flag. If you want an unsigned number use %u:

printf("%u\n",b);
atomSmasher
  • 1,465
  • 2
  • 15
  • 37