http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52703

             Bug #: 52703
           Summary: -Wsign-conversion warns for unsigned short promoted to
                    int and assigned to unsigned
    Classification: Unclassified
           Product: gcc
           Version: 4.6.2
            Status: UNCONFIRMED
          Severity: trivial
          Priority: P3
         Component: c++
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: deusexsophism...@gmail.com


$ g++ test.cpp -Wsign-conversion
test.cpp: In function ‘int main()’:
test.cpp:7:19: warning: conversion to ‘unsigned int’ from ‘int’ may change the
sign of the result [-Wsign-conversion]
test.cpp:8:10: warning: conversion to ‘unsigned int’ from ‘int’ may change the
sign of the result [-Wsign-conversion]


unsigned f (unsigned x) {
    return x;
}

int main () {
    unsigned short a = 0;
    unsigned b = a + 1;
    f (a + 1);
    return 0;
}




The implicit conversion to int from unsigned short causes gcc to think that the
result of a + 1 could theoretically be a negative value (since it's an int).
However, it cannot be no matter what value a has (since we know it's unsigned).
signed overflow is undefined, so we don't have to worry about a + (integral
constant expression) > INT_MAX.

Note that the bug does not trigger if + 1 is replaced with + 0. My guess is
that the removal of addition by 0 happens before this warning is checked. It
also does not trigger if a is declared `unsigned short const` instead of just
`unsigned short`.



$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.6.2/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man
--infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla
--enable-bootstrap --enable-shared --enable-threads=posix
--enable-checking=release --with-system-zlib --enable-__cxa_atexit
--disable-libunwind-exceptions --enable-gnu-unique-object
--enable-linker-build-id
--enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin
--enable-java-awt=gtk --disable-dssi
--with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre
--enable-libgcj-multifile --enable-java-maintainer-mode
--with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib
--with-ppl --with-cloog --with-tune=generic --with-arch_32=i686
--build=x86_64-redhat-linux
Thread model: posix
gcc version 4.6.2 20111027 (Red Hat 4.6.2-1) (GCC)

Reply via email to