How can I know what is the maximum assignable value for a variable from the the type of "unsigned long int"?
3 Answers
The obvious way would be to use std::numeric_limits<unsigned long>::max();
-
2
-
@jvriesem: much of the reason it exists is because the value could vary (but it must have at least 32- bit range, so the minimum allowed value is a tad over 4 billion). Feb 18, 2020 at 5:37
Another way to find out would be:
unsigned long int i = (unsigned long int) -1;
printf("%lu\n", i);
-
3doesn't work on 1's complement machines (where -0 would be the max) Aug 18, 2013 at 18:17
-
4@TemplateRex -
(unsigned long)-1is always the largest value that can be represented in anunsigned long. Regardless of the underlying hardware, unsigned arithmetic "shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer." [basic.fundamental]/4. Aug 18, 2013 at 19:16 -
1@TemplateRex - you're looking at how underflow might be simply handled, but the standard says what it has to do, and if that simple implementation doesn't do it, then the implementation is wrong. Aug 18, 2013 at 23:46
-
1@PeteBecker You are right, but actually the relevant Standard quote is [conv.integral/2]: If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2 n 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 ]. Aug 19, 2013 at 6:33
-
1