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

前端 未结 3 997
栀梦
栀梦 2021-01-04 04:53

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. How

相关标签:
3条回答
  • 2021-01-04 05:05

    Use -Wconversion:

    ~/src> gcc -Wconversion -Werror -Wall -Wextra -pedantic -o signwarn signwarn.c
    cc1: warnings being treated as errors
    signwarn.c: In function 'main':
    signwarn.c:5: error: negative integer implicitly converted to unsigned type
    

    I guess the thing here is that gcc is actually pretty good at generating warnings, but it defaults to not doing so for (sometimes unexpected) cases. It's a good idea to browse through the available warnings and choose a set of options that generate those you feel would help. Or just all of them, and polish that code until it shines! :)

    0 讨论(0)
  • 2021-01-04 05:14

    Using (unsigned)-1 is an often used way to set all bits and sometimes even quoted as reason for this (mis)feature of C, even by people who should know better . It's neither obvious nor portable -- the expression you want to use to set all bits is ~0 .

    0 讨论(0)
  • 2021-01-04 05:15

    The ability to convert negative value to unsigned type is a feature of C language. For this reason, the warning is not issued by default. You have to request it explicitly, if you so desire.

    As for what your program outputs... Using %d format specifier of printf with an unsigned value that lies beyond the range of type int results in undefined behavior, which is what you really observed in your experiment.

    0 讨论(0)
提交回复
热议问题