简体   繁体   English

删除左移位数> =类型警告的宽度

[英]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? 因为uint32_t的大小是32位还是不是?

Sizeof returns the size in bytes. Sizeof以字节为单位返回大小。 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 您可能会发现它是4而不是32.如果您想要以位为单位的大小,您可以乘以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. sizeof(uint32_t)在你的系统中是4,所以第一个代码得到正确的操作数为(4-8),这是一个负数,因此警告。

In the second code it is a positive number, so no warning. 在第二个代码中,它是一个正数,所以没有警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM