Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write negative one as an unsigned literal in C++

In my program, I often use -1 (aka UINT_MAX) as a value for unsigned variables to denote something special. I also compare against this value. Turning on higher levels of warning messages reveals that compilers (both VS and GCC) do not like this syntax.

// warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch
unsigned a = -1;

// warning C4146: unary minus operator applied to unsigned type, result still unsigned
unsigned b = -1U;

// fine but messy
unsigned c = unsigned(-1);

// no warning on VS, signed/unsigned comparison warning with GCC
if (a == -1)
{
  std::cout << "check\n";
}

Question 1: Is the syntax given above (each case) legitimate C++ code?

Question 2: Do I really have to write unsigned(-1) everywhere I use this value to assign/compare to an unsigned int or is there a cleaner way that will not trigger a compiler warning?

like image 818
devtk Avatar asked Oct 22 '25 23:10

devtk


1 Answers

By its very nature, you cannot write negative one as an unsigned literal in C++ or any other language.

You don't mean -1, you mean std::numeric_limits<unsigned int>::max().

#include <iostream>
#include <limits>

int main()
{
    unsigned a = std::numeric_limits<unsigned int>::max();

    if (a == std::numeric_limits<unsigned int>::max())
    {
        std::cout << "check " << a << "\n";
    }
}

The C++11 standard made this function constexpr, which guarantees that the function is a compile-time constant. (Further reading).

If you want to avoid calculating this for every iteration of a loop using an older compiler, create a const outside the loop and compare this:

const unsigned int magic_number = std::numeric_limits<unsigned int>::max();

    // [...]
    if (a == magic_number)
like image 64
Johnsyweb Avatar answered Oct 24 '25 14:10

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!