简体   繁体   中英

why the output of following c program is -10

#include <stdio.h>

int main() {
    unsigned int a = -10;
    printf("a=%d\n", a);

    return 0;
}

The above code is printing -10 for signed int . If the both signed and unsigned are printing the -10 then what is difference between them?

You actually have undefined behavior in that code.

The "%d" format is for plain signed int , and mismatching format specifier and argument leads to UB.

Since printf doesn't have any idea of the real types being passed, it has to rely only on the format specifiers. So what probably happens is that the printf function simply treats the value as a plain signed int and print it as such.

printf doesn't know about the type of the argument that you're giving it. With %d you're telling it that it's a signed int , which is wrong. That's undefined behavior - anything could happen. What will likely happen is that it's just interpreting that memory as signed int anyway, and with the unsigned int a=-10; you set the unsigned int to what will be interpreted as -10 when read as signed int . For further info on what happens with that assignment of a negative number to an unsigned type, check out this answer .

You should use

printf("a= %u \\n",a);

to print "a" as an unsigned integer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM