views:

375

answers:

2

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.

A: 

I would strongly suggest investing in PC-lint/FlexeLint from Gimpel. The software is made for catching things like this that the compiler just isn't. It is relatively inexpensive and well worth the price. There is an online demo on the site that you can use to evaluate it, here is what it reports for the line in question from your example:

diy.cpp  14  Info 734: Loss of precision (arg. no. 1) (31 bits to 15 bits)
Robert Gamble
+5  A: 

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)

Reed Hedges
Aha--so it's just that 4.2.4 is too "old" to make it warn like it should, and 4.3.2 works (I'm making a couple assumptions here, but I think it's safe to say because I'm using Ubuntu and I saw some notes on the issue that make it seem reasonable to think that this is just something fixed in 4.3+.
John Zwinck
I've now tried with GCC 4.3.2 on an Ubuntu Intrepid machine, and -Wconversion does what I want. Hooray. But boo for 4.2.4 not working.
John Zwinck