38

Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

39
  • 41
    Seeing - and unsigned on the same line is guaranteed to raise a few eyebrows.
    – Ron
    Dec 7, 2017 at 15:32
  • 6
    You don't need to repeat yourself if you use auto.
    – Quentin
    Dec 7, 2017 at 15:32
  • 8
    I voted to reopen because this question is not an exact duplicate of the purported original. The other question discusses the behavior of arithmetic when values exceed the range of an unsigned integer type. While this question involves that, it asks a different question about the semantics of using -1. Dec 7, 2017 at 15:37
  • 12
    Ron's comment is more than just a comment. While -1 might be technically correct (see Eric's answer), from a clean code standpoint it isn't. Figuring out whether -1 is an error here took you a question, and Eric a looking-up in the standard. unsigned short i = USHRT_MAX would require neither, and be more explicit about the statement's intended purpose.
    – DevSolar
    Dec 7, 2017 at 15:42
  • 5
    The question may apply to multiple languages, yet the answer is not necessarily the same for C and C++. Selecting 1 language would reduce the unnecessary broadness of this question. Dec 7, 2017 at 15:44

5 Answers 5

29

Regarding conversions of integers, C 2011 [draft N1570] 6.3.1.3 2 says

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Thus, converting -1 to an unsigned integer type necessarily produces the maximum value of that type.

There may be issues with using -1 in various contexts where it is not immediately converted to the desired type. If it is immediately converted to the desired unsigned integer type, as by assignment or explicit conversion, then the result is clear. However, if it is a part of an expression, its type is int, and it behaves like an int until converted. In contrast, UINT_MAX has the type unsigned int, so it behaves like an unsigned int.

As chux points out in a comment, USHRT_MAX effectively has a type of int, so even the named limits are not fully safe from type issues.

4
  • Concerning "UINT_MAX has the type unsigned int ..." does not address OP's case of unsigned short. This suggests USHRT_MAX whose type, AFIAK, is not specified. (C: Perhaps could be int, unsigned, unsigned short, ...). Dec 7, 2017 at 16:45
  • 2
    @chux: That is a good point. The type is specified; these macros are “expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions,” but that means USHRT_MAX may be an int, so it may behave unexpectedly if you are expecting an unsigned type. Dec 7, 2017 at 16:59
  • It might be beneficial to reference other standards to prove this, but for the record, as far as I can recall, this behavior was well-defined for all C standards as of this writing. If I remember right, C99 has the same text. C89's standard text does not include this exact phrase but it is implied by the rules for integer promotions/conversions, as I understand it. And I think all C++ standards have been aligned with this behavior.
    – mtraceur
    Dec 7, 2017 at 21:34
  • Thank you for your answer. However, there was a long discussion about the question, it seems it is better to change it to c++ only. I have upvoted your answer though and it helped me. Dec 13, 2017 at 19:18
18

Not using the standard way or not clearly showing the intent is often a bad idea that we pay later

I would suggest:

auto i = std::numeric_limits<unsigned int>::max(); 

or @jamesdin suggested a certainly better one, closer to the C habits:

unsigned int i = std::numeric_limits<decltype(i)>::max(); 

Your colleague argument is not admissible. Changing int -> long int, as bellow:

auto i = std::numeric_limits<unsigned long int>::max(); 
  • does not require extra work compared to the -1 solution (thanks to the use of auto).
  • the '-1' solution does not directly reflect our intent, hence it possibly has harmful consequences. Consider this code snippet:

.

using index_t = unsigned int;

... now in another file (or far away from the previous line) ...

const index_t max_index = -1;

First, we do not understand why max_index is -1. Worst, if someone wants to improve the code and define

 using index_t = ptrdiff_t;

=> then the statement max_index=-1 is not the max anymore and you get a buggy code. Again this can not happen with something like:

const index_t max_index = std::numeric_limits<index_t>::max();

CAVEAT: nevertheless there is a caveat when using std::numeric_limits. It has nothing to do with integers, but is related to floating point numbers.

std::cout << "\ndouble lowest: "
          << std::numeric_limits<double>::lowest()
          << "\ndouble min   : "
          << std::numeric_limits<double>::min() << '\n';

prints:

double lowest: -1.79769e+308    
double min   :  2.22507e-308  <-- maybe you expected -1.79769e+308 here!
  • min returns the smallest finite value of the given type
  • lowest returns the lowest finite value of the given type

Always interesting to remember that, as it can be a source of bug if we do not pay attention to (using min instead of lowest).

5
  • 1
    2.22507e-308 does not look like the "smallest finite value of the given type". I'd expect 4.940656e-324. Perhaps it is the smallest normal value of the given type? Ref: min returns the minimum positive normalized value Dec 7, 2017 at 18:07
  • @chux I have cut/copy cppreference. But I do agree, it is the smallest normalized number here. Dec 7, 2017 at 18:12
  • 2
    Or alternatively: unsigned int i = std::numeric_limits<decltype(i)>::max();
    – jamesdlin
    Dec 8, 2017 at 4:04
  • @jamesdin your syntax is certainly better as it's closer to the C usual one -> I will mention your suggestion in my post Dec 8, 2017 at 7:57
  • 1
    @underscore_d I have completely rewritten this part. Thanks for pointing out this unclear wording. Dec 8, 2017 at 10:25
16

Is -1 correct for using as maximum value of an unsigned integer?

Yes, it is functionally correct when used as a direct assignment/initialization. Yet often looks questionable @Ron.

Constants from limits.h or std::numeric_limits convey more code understanding, yet need maintenance should the type of i change.


[Note] OP later drop the C tag.

To add an alternative to assigning a maximum value (available in C11) that helps reduce code maintenance:

Use the loved/hated _Generic

#define info_max(X) _Generic((X), \
  long double: LDBL_MAX, \
  double: DBL_MAX, \
  float: FLT_MAX, \
  unsigned long long: ULLONG_MAX, \
  long long: LLONG_MAX, \
  unsigned long: ULONG_MAX, \
  long: LONG_MAX, \
  unsigned: UINT_MAX, \
  int: INT_MAX, \
  unsigned short: USHRT_MAX, \
  short: SHRT_MAX, \
  unsigned char: UCHAR_MAX, \
  signed char: SCHAR_MAX, \
  char: CHAR_MAX, \
  _Bool: 1, \
  default: 1/0 \
  )

int main() {
  ...
  some_basic_type i = info_max(i);
  ...
}

The above macro info_max() have limitations concerning types like size_t, intmax_t, etc. that may not be enumerated in the above list. There are more complex macros that can cope with that. The idea here is illustrative.

10
  • Good point about the constants (other than -1) breaking when the unsigned int size changes unless using a macro like yours.
    – Dave S
    Dec 7, 2017 at 18:00
  • The -1 also needs maintenance if the type changes to a signed one.
    – jpmc26
    Dec 7, 2017 at 21:48
  • @jpmc26 True about -1 and a change to some signed integer type - which is covered with info_max(i). Yet OP's question is primarily about various unsigned integer types and that's where -1 assignment reduces maintenance. IMO, any use of some_unsigned_type x = -1;, at least, obligates an explaining comment. I also see it as a minor problem as a compiler settings may warn about the sign-ess change and I like warning free code. Dec 7, 2017 at 22:16
  • @chux Right, not really arguing that this definitively makes one option better than another. Just saying that it's questionable whether -1 needs less maintenance if you're talking about type changes, which undermines the perceived advantage it might provide. The macro does seem to eliminate the maintenance concern, at the cost of having a custom macro that someone may then need to go read. Trade-offs everywhere.
    – jpmc26
    Dec 8, 2017 at 1:25
  • 1
    Does it? I'm not up on _Generic, but by my current understanding, dividing by zero just invokes undefined behaviour, which is not a way to trap errors, but rather to heap additional ones onto the problem. Dec 8, 2017 at 10:58
9

The technical side has been covered by other answers; and while you focus on technical correctness in your question, pointing out the cleanness aspect again is important, because imo that’s the much more important point.

The major reason why it is a bad idea to use that particular trickery is: The code is ambiguous. It is unclear whether someone used the unsigned trickery intentionally or made a mistake and actually wanted to initialize a signed variable to -1. Should your colleague mention a comment after you present this argument, tell him to stop being silly. :)

I’m actually slightly baffled that someone would even consider this trick in earnest. There’s an unambigous, intuitive and idiomatic way to set a value to its max in C: the _MAX macros. And there’s an additional, equally unambigous, intuitive and idiomatic way in C++ that provides some more type safety: numeric_limits. That -1 trick is a classic case of being clever.

5
  • 2
    Use of _MAX macros oblige code maintenance should i change from unsigned short to unsigned long. The some_unsigned_type i = -1; "trick" does not need that maintenance. This does not mean that i = -1; is a great general purpose idea. Yet it may make sense is select cases that are not silly. The larger context is need to make good judgment - something OP has not presented. Dec 7, 2017 at 16:54
  • 3
    @chux True about the context. But I’m confident that legitimate cases of using this trick are few and far between. And even then I wouldn’t want to see it in its naked form, but wrapped in a macro or using a named constant to get rid of the ambiguity.
    – besc
    Dec 7, 2017 at 17:13
  • I agree on all points in the comment. Dec 7, 2017 at 17:15
  • 2
    I have used the trick myself, although usually as 0 - 1 rather than -1. I just think it looks more intentional that way.
    – Ian Abbott
    Dec 7, 2017 at 17:37
  • I have encountered only one usecase of the -1 trick in my C coding that I consider defensible: when abstracting code that has to be repeated for all unsigned integral types into a type generic macro because you need to support C89 or C99 compilers (so you have neither C++'s nor C11's type generic capabilities to help you).
    – mtraceur
    Dec 7, 2017 at 21:41
8

The C++ standard says this about signed to unsigned conversions ([conv.integral]/2):

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

So yes, converting -1 to an n-bit unsigned integer will always give you 2n-1, regardless of which signed integer type the -1 started as.

Whether or not unsigned x = -1; is more or less readable than unsigned x = UINT_MAX; though is another discussion (there's definitely the chance that it'll raise some eyebrows, maybe even your own when you look at your own code later;).

1
  • 1
    I think it's this language that defines the wide unsigned = narrower signed case as performing sign extension. To get zero extension, you have to cast to a narrow unsigned before assigning. examples for x86-64: godbolt.org/g/yHj8fC (which uses 2's complement, so this only demonstrates that you get sign-extension (e.g. to all-ones, not 0x00000000FFFFFFFF) Dec 7, 2017 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.