Max Max - 1 year ago 74
C Question

Why is code "unsigned int n = -1 " have the result "n = -1"?

I have learn that the limit of type unsigned int is 0 -> 2^32 - 1 (Win 32bit) but when I build code

unsigned int n = -1;

it's not make error and the result is n = -1 .I don't understand why have that result . Please explain for me. Any help is appreciated.Thanks in advance.

Answer Source

it's not make error and the result is n = -1

Yeah you won't get an error. But if you try to print result of that as unsigned integer, you will get -1 interpreted as unsigned integer, which will be maximum integer value.

In your case, you decided to print it as signed integer using %d format specifier, in which case IMO you triggered undefined behavior, because of using wrong format specifier in printf. For printing unsigned integers you should use %u.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download