简体   繁体   中英

removing left shift count >= width of type warning

Why does this code generates a warning :

niko: snippets $ cat leftshift.c 
#include <stdint.h>
#include <stdio.h>

int main(void) {

    uint32_t var1;
    uint32_t var2;

    var1=55;
    var2=var1 << (sizeof(uint32_t)-8);

    printf("%d\n",var2);
}
niko: snippets $ gcc -g -Wl,--warn-common -ffunction-sections -fshort-enums -fdata-sections -Wall -Wextra -Wunreachable-code -Wmissing-prototypes -Wmissing-declarations -Wunused -Winline -Wstrict-prototypes -Wimplicit-function-declaration -Wformat  -D_GNU_SOURCE -fshort-enums -std=c99  -c leftshift.c 
leftshift.c: In function ‘main’:
leftshift.c:10:12: warning: left shift count >= width of type [-Wshift-count-overflow]
  var2=var1 << (sizeof(uint32_t)-8);
            ^
niko: snippets $ 

While this same code does not:

niko: snippets $ cat leftshift.c 
#include <stdint.h>
#include <stdio.h>

int main(void) {

    uint32_t var1;
    uint32_t var2;

    var1=55;
    var2=var1 << (32-8);

    printf("%d\n",var2);
}
niko: snippets $ gcc -g -Wl,--warn-common -ffunction-sections -fshort-enums -fdata-sections -Wall -Wextra -Wunreachable-code -Wmissing-prototypes -Wmissing-declarations -Wunused -Winline -Wstrict-prototypes -Wimplicit-function-declaration -Wformat  -D_GNU_SOURCE -fshort-enums -std=c99  -c leftshift.c 
niko: snippets $ 

Is there something wrong with GCC ? Because size of uint32_t is 32 bits or isn't it?

Sizeof returns the size in bytes. You should try this:

printf("%d\n", sizeof(uint32_t));

You'll probably find that it's 4, not 32. If you want the size in bits, you can multiply by 8: sizeof(uint32_t) * 8

sizeof(uint32_t) is 4 in your system, so the first code gets the right operand as (4-8) which is a negative number, hence the warning.

In the second code it is a positive number, so no warning.

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