Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make GCC warn on passing too-wide types to functions?

Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither gcc nor g++ does, even with all the warnings options I could think of: -pedantic -Wall -Wextra

#include <stdio.h>

short f(short x)
{
    return x;
}

int main()
{
    long x = 0x10000007;   /* bigger than short */
    printf("%d\n", f(x));  /* hoping for a warning here */
    return 0;
}

Is there a way to make gcc and g++ warn about this? On a side note, do you have another compiler which warns about this by default or in a fairly common extra-warnings configuration?

Note: I'm using GCC (both C and C++ compilers) version 4.2.4.

Edit: I just found that gcc -Wconversion does the trick, but the same option to g++ doesn't, and I'm really using C++ here, so I need a solution for g++ (and am now wondering why -Wconversion doesn't seem to be it).

Edit: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389 suggests that this may be fixed in g++ 4.4...maybe? It's not clear to me yet if it's the same issue and/or if the fix is really coming in that version. Maybe someone with 4.3 or 4.4 can try my test case.

like image 550
John Zwinck Avatar asked Nov 21 '08 20:11

John Zwinck


People also ask

Which option of GCC inhibit all warning messages?

-Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. Suppress warning messages emitted by #warning directives.

Which GCC flag is used to enable all compiler warnings?

gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.

Which flags would you pass to your C++ compiler so it warns you about implicit conversions?

The C++ compiler comes with a lot of useful warnings that warn you about potential errors and issues in your code. You always want to compile with warnings. A warning flag starts with -W and then the name of the warning, for example -Wconversion which warns about implicit conversions.


1 Answers

Use -Wconversion -- the problem is an implicit cast (conversion) from long x to short when the function f(short x) is called [not printf], and -Wconversion will say something like "cast from long to short may alter value".

..

Edit: just saw your note. -Wconversion results in a warning for me, using g++ 4.3.2 on Linux... (4.3.2-1 on Debian)

like image 95
Reed Hedges Avatar answered Nov 15 '22 11:11

Reed Hedges