Why is there an unsigned int below zero?

I just tried to lower the unsigned int below 0. To my surprise, this works!

#include<stdio.h>

int main(void)
{
        unsigned int foo = 5;
        foo -= 10;
        printf("%d", foo);
        return 0;
}

Compiled with

clang -Weverything main.c

This program returns

-5

As this post and my personal knowledge say, this is not possible. But why does this work? Am I missing something? Is It Due To Undefined Behavior? Or is it printf? Or something else?

+4
source share
3 answers

This program uses printfto interpret the value unsigned intas a signed integer. Although this is not a problem when a value is unsigned intalso suitable for int, this behavior is undefined:

- , undefined

: "", , unsigned int. , , , printf , .

?

. Q & A .

+7

printf() foo . % d % u.

: dasblinkenlight, undefined. , , , . , , , .

+4

. , 2 , . ///, . C, , , . , , .

0

All Articles