Why t he value of unsigned inter is displayed as signed?

Debojit Acharjee 455 Reputation points
2023-05-30T05:55:17.63+00:00

In the following program -1 was assigned to unsigned variable 'a' and 'b' but why the value of 'a' is printed as -1? The value of 'b' is also not printed as 1 even after using the unsigned specifier '%u".

#include <stdio.h>

int main ()
{
  unsigned int a;
  unsigned int b;

  a = -1;

  b = a;

  printf ("Signed value of a: %d\nUnsigned value of b: %u", a, b);

  return 0;

}

Output:

Signed value of a: -1

Unsigned value of b: 4294967295

Developer technologies | C++
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Barry Schwarz 3,746 Reputation points
    2023-05-30T06:09:54.1933333+00:00

    When you lie to printf, what do you expect?

    You told printf to print the value of a using %d as the format specification. Go to your library reference and learn what type of value %d requires. Did you provide a value of that type? Obviously not.

    printf printed the correct value for b. Go to your language reference and learn what happens when you assign a value that is out of range to an unsigned integer.

    You are asking a lot of questions about why C does not do what you expect. It is time to realize that many of your expectations are not based on what the standard requires the language to do.

    3 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.