Search code examples
c++error-handlingcompiler-warningsuint32int32

C++: Setting a uint32 to an int32 (negative value)


I am debating whether I can get rid of a compiler warning or not. The warning comes from comparing an uint32 to -1.

Now just from glancing at it this seems like an unwise thing to do since uint32 should never be negative yet I didn't write this code and am not as familiar with the c++ way of doing things, so I am asking you. Here is some example code to illustrate what's happening.

  bool isMyAddressValid = false;
  unsigned int myAddress(-1);
  unsigned int translatedAddress;

  if(isMyAddressValid)
  {
      translatedAddress = 500;
  }
  else
  {
      translatedAddress = -1;
  }

  myAddress = translatedAddress;

  if(myAddress == -1)
  {
      std::cout << "ERROR OCCURED";
  }
  else
  {
      std::cout << "SUCCESS";
  }`

So is this valid code? Is this come Cism that I do not properly understand?


Solution

  • Setting an unsigned type to -1 is the idiomatic way of setting it to its maximum possible value, regardless of the number of bits in the type.

    A clumsier but perhaps clearer way would be to write

    translatedAddresss = std::numeric_limits<decltype(translatedAddresss)>::max();