Why doesn't GCC produce a warning when assigning a signed literal to an unsigned type?

Posted by maerics on Stack Overflow See other posts from Stack Overflow or by maerics
Published on 2010-05-05T08:19:06Z Indexed on 2010/05/05 8:28 UTC
Read the original article Hit count: 272

Filed under:
|
|
|

Several questions on this website reveal pitfalls when mixing signed and unsigned types and most compilers seem to do a good job about generating warnings of this type. However, GCC doesn't seem to care when assigning a signed constant to an unsigned type! Consider the following program:

/* foo.c */
#include <stdio.h>
int main(void)
{
    unsigned int x=20, y=-30;
    if (x > y) {
        printf("%d > %d\n", x, y);
    } else {
        printf("%d <= %d\n", x, y);
    }
    return 0;
}

Compilation with GCC 4.2.1 as below produces no output on the console:

gcc -Werror -Wall -Wextra -pedantic foo.c -o foo

The resulting executable generates the following output:

$ ./foo
20 <= -30

Is there some reason that GCC doesn't generate any warning or error message when assigning the signed value -30 to the unsigned integer variable y?

© Stack Overflow or respective owner

Related posts about c

    Related posts about gcc