Sunday, May 1, 2011

Is there a gcc 4.2 warning similar to Visual Studio's regarding possible loss of data?

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?

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

    Evan Teran : better yet, follow the link in that bug entry: http://gcc.gnu.org/wiki/Wcoercion
    Lyndsey Ferguson : This isn't actually answering my question. But thanks for looking.
  • 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
    
  • 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.

0 comments:

Post a Comment