Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to assign -1 to an unsigned int to get the max value?

Tags:

c++

unsigned

Is it safe to assign -1 to an unsigned int, or other unsigned c++ data type, if I need to get the max value?

Is there any situation where it won't give me the highest value an unsigned data type can contain?

like image 608
Spectralist Avatar asked Apr 25 '12 06:04

Spectralist


People also ask

Is it good practice for unsigned int?

The Google C++ style guide recommends avoiding unsigned integers except in situations that definitely require it (for example: file formats often store sizes in uint32_t or uint64_t -- no point in wasting a signedness bit that will never be used).

What is the maximum possible value of an unsigned integer?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

Can an unsigned int overflow?

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

What is the max value that can be stored in an unsigned int in C?

It takes a size of 32 bits. A maximum integer value that can be stored in an unsigned int data type is typically 4, 294, 967, 295, around 232 – 1(but is compiler dependent). The maximum value that can be stored in unsigned int is stored as a constant in the <climits> header file.


1 Answers

To be on a safe side, use std::numeric_limits<unsigned int>::max(). Casting -1 to unsigned would work on mainstream platforms, but it is not guaranteed by the standard AFAIR.

UPD: I'll correct myself. (unsigned)-1 is required to be UINT_MAX in C, see the answer here

like image 53
Andrey Avatar answered Nov 14 '22 23:11

Andrey