Angus
Angus

Reputation: 12621

When will an unsigned int variable becomes negative

I was going through the existing code and when debugging the UTC time which is declared as

unsigned int utc_time;

I could get some positive integer every time by which I would be sure that I get the time. But suddenly in the code I got a negative value for the variable which is declared as an unsigned integer.

Please help me to understand what might be the reason.

Upvotes: 3

Views: 1402

Answers (4)

mikek3332002
mikek3332002

Reputation: 3562

Make sure you using

printf("%u", utc_time);

to display it


In response to the comment %u displays the varible as an unsigned int where as %i or %d will display the varible as a signed int.

Upvotes: 3

AusCBloke
AusCBloke

Reputation: 18492

When it's cast or treated as a signed type. You probably printed your unsigned int as an int, and the bit sequence of the unsigned would have corresponded to a negative signed value.

ie. Perhaps you did:

unsigned int utc_time;
...
printf("%d", utc_time);

Where %d is for signed integers, compared to %u which is used for unsigned. Anyway if you show us the code we'll be able to tell you for certain.

There's no notion of positive or negative in an unsigned variable.

Upvotes: 3

maerics
maerics

Reputation: 156444

Negative numbers in most (all?) C programs are represented as a two's complement of the unsigned number plus one. It's possible that your debugger or a program listing the values doesn't show it as an unsigned type so you see it's two's complement.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881653

Unsigned integers, by their very nature, can never be negative.

You may end up with a negative value if you cast it to a signed integer, or simply assign the value to a signed integer, or even incorrectly treat it as signed, such as with:

#include <stdio.h>

int main (void) {
    unsigned int u = 3333333333u;
    printf ("unsigned = %u, signed = %d\n", u, u);
    return 0;
}

which outputs:

unsigned = 3333333333, signed = -961633963

on my 32-bit integer system.

Upvotes: 9

Related Questions