Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Lyndsey Ferguson Avatar asked Apr 21 '09 21:04

Lyndsey Ferguson


3 Answers

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.

like image 90
user9876 Avatar answered Nov 09 '22 13:11

user9876


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

like image 35
schnaader Avatar answered Nov 09 '22 13:11

schnaader


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
like image 41
James Hopkin Avatar answered Nov 09 '22 13:11

James Hopkin