views:

493

answers:

3

Is there a flag for gcc such that conversions from a long to a short will generate a warning about a possible loss of data?

I'm working on a C++ application that is compiled for both Visual Studio (2005) and GCC 4.2 (for Mac OS X).

The warnings that Visual Studio prints out follow this pattern:

: warning C4244: 'argument' : conversion from 'long' to 'short', possible loss of data

I've tried -Wconversion, but that isn't quite what I'm looking for. The only thing I've been able to find so far is an experimental flag, -Wcoercion, which is associated with GCC 4.3 (which I'm not sure if we want to invest in quite yet).

April 22, 2009 @ 11:00 EST Edit:To clarify, I want to see that warning. We have code where we want to know when a data loss would occur. If I have the code:

unsigned long value1 = LONG_MAX;
std::cout << "value1: " << value1 << std::endl;

unsigned short value2 = value1;
std::cout << "value2: " << value2 << std::endl;

I get this expected result:

  value1: 2147483647
  value2: 65535

In our code, we have special asserts put in place that perform the coercion and warn us if the executed-code would result in a loss of data. We found the places in our large code base using Visual Studio's warnings.

Is there any way we can generate these warnings in gcc 4.2?

+4  A: 

Look at this GCC bug entry, perhaps it helps in understanding why converting from long to short doesn't lead to a warning.

schnaader
better yet, follow the link in that bug entry: http://gcc.gnu.org/wiki/Wcoercion
Evan Teran
This isn't actually answering my question. But thanks for looking.
Lyndsey Ferguson
+3  A: 

Use -Wconversion. You seem to need this even if you already specify -Wall.

It definitely works in gcc4.3. If it wasn't fixed by version 4.2, you'll have to upgrade to get it.

Example warning:

warning: conversion to 'short int' from 'int' may alter its value
James Hopkin
+2  A: 

This feature is not supported in GCC 4.2, but it has been added in GCC 4.3. Wiki page explaining it.

Thanks to schnaader and Evan Teran for providing the links that led me there.

user9876