Search code examples
cgccgcc-warning

How to make gcc complain about comparison of char with 256


I found the following code on codegolf.stackexchange to print a code table for ASCII characters:

#include <stdio.h>

int main(){
    char i;
    for(i = 0; i < 256; i++){
        printf("%3d 0x%2x: %c\n", i, i, i);
    }
    return 0;
}

Since chars store single bytes in them, they are always < 256 and the loop never terminates. I would like to detect this upon compilation.

Nicely, clang gives the following warning:

a.c:5:18: warning: comparison of constant 256 with expression of type 'char' is always true [-Wtautological-constant-out-of-range-compare]
for(i = 0; i < 256; i++){
           ~ ^ ~~~

However, neither gcc nor gcc -Wall give any warning of any sort. Is there any set of command line options I can give to turn on this kind of warnings? Or is it not possible in gcc?


Solution

  • -Wtype-limits (or -Wextra) should trigger this warning