Nulik Nulik - 2 months ago 12
C Question

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?

Answer

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