5

Is there a way of guarding against the resulting binary from the code in this question? Ideally by way of an error at compile time. Example code from the question:

unsigned int nVal = 0;
nVal = -5;  // no error!
Community
  • 1
  • 1
Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
  • `compiler error` at runtime? *Assignment* happens at runtime. – Nawaz Sep 20 '11 at 11:40
  • 1
    There might be a way by exploiting convoluted conversion rules, but it would mean changing your code so it doesn't use `unsigned int` anymore, but something like `EnforcedUnsignedInt` with other intermediate classes to cause different code generation when using `operator =` with signed / unsigned. Verdict: Not practical / realistic. – tenfour Sep 20 '11 at 11:45
  • 1
    The initial assignment of `0` (which is signed), rather than `0u`, would presumably also generate the warning/error you want. – Graham Borland Sep 20 '11 at 11:48

2 Answers2

10

If you are using g++, the switch -Wsign-conversion will warn about the conversion, and -Werror will make that warning an error.

iammilind
  • 68,093
  • 33
  • 169
  • 336
thiton
  • 35,651
  • 4
  • 70
  • 100
  • Perfect, just what I was after! – Samuel Harmer Sep 20 '11 at 11:48
  • In Visual Studio, you can also turn on a "treat warnings as errors" feature on a project build options. And the compiler should raise a warning for possible loss of data when converting from int to unsigned int. – Seb Sep 20 '11 at 11:50
4

Edit: Apart from @thiton's answer.

With the simple assignment it's not possible. However, if you assign the value in a little special wrapped way, then it can help. i.e.

nVal = -5;

should be replaced with,

Assign<-5>(nVal);

Where, Assign() looks like,

template<int VAL>
void Assign (unsigned int &nVal)
{
  typedef int arr[(VAL >= 0) 1 : -1];
  nVal = VAL;
}

Demo.

iammilind
  • 68,093
  • 33
  • 169
  • 336