Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC - shouldn't a warning be issued when assigning an int to a char?

Tags:

c

gcc

mingw

I've recently set up a MinGW + MSYS environment on my laptop to check how things are with Netbeans C/C++ support. Everything seems to work fine, however, during my testing I have noticed a difference between GCC and Microsoft's cl.exe compiler.

Here's a sample program:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void) {
    int i_max = INT_MAX;
    char c_max = CHAR_MAX, c;

    c = i_max;
    printf("i_max: %d, c_max: %d, c: %d\n", i_max, c_max, c);
    return EXIT_SUCCESS;
}

The output is:

i_max: 2147483647, c_max: 127, c: -1

As you can see in the code above, I assign an int to a char. Shouldn't this produce a warning that a possible data loss may occur? Microsoft's compiler (which I have configured to be very strict) does issue the warning while GCC doesn't.

Here are the GCC options I use:

-g -Werror -ansi -pedantic -Wall -Wextra

Am I missing some GCC option to make the compile time checks even stricter?

like image 252
Ree Avatar asked Nov 13 '09 16:11

Ree


1 Answers

You're looking for

-Wconversion

You'd have to ask a gcc developer for the specific reasons why some warnings aren't included in -Wall or -Wextra.

Anyway, these are the flags I use:

-Wall -Wextra -Wmissing-prototypes -Wmissing-declarations -Wshadow
-Wpointer-arith -Wcast-align -Wwrite-strings -Wredundant-decls -Wnested-externs
-Winline -Wno-long-long -Wconversion -Wstrict-prototypes

As other's have pointed out, the behaviour of -Wconversion changed with version 4.3 - the old warning about prototypes forcing a type conversion is now available as -Wtraditional-conversion.

like image 88
Christoph Avatar answered Sep 22 '22 16:09

Christoph