0

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?

TeeseCaprice
  • 55
  • 1
  • 13

3 Answers3

1

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();
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

If it is in your arsenal of libraries, I would use std::optional or boost::optional

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

The code is valid according to the standard, both assignment and equality check applies integer conversions on its operands. It is, however, a C-ism to use a sentinel value, I would use an exception instead.

Johan
  • 3,667
  • 6
  • 20
  • 25