Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int max = ~0; What does it mean?

int max = ~0;

What does it mean?

like image 753
Ravit Teja Avatar asked Nov 27 '22 07:11

Ravit Teja


2 Answers

The ~ operator is the unary bitwise complement operator which computes the bitwise complement. This means that it reverses all the bits in its argument (0s become 1s and 1s become 0s). Thus,

int max = ~0;

which is setting max to the negation of the 32-bit value 0000 0000 0000 0000 0000 0000 0000 0000 resulting in 1111 1111 1111 1111 1111 1111 1111 1111. As we are storing this result in an Int32, this is the same as -1.

Whether or not it is better to say

int max = ~0;

or

int max = -1;

depends on the context. If the point of max is to have a number all of whose bits are 1 I would choose the former. If the point of max is to compute the maximum of a list of non-negative integers, I would choose the latter (well, I'd prefer int max = Int32.MinValue; and even more so, I'd just prefer int max = list.Max();).

like image 168
jason Avatar answered Dec 06 '22 17:12

jason


The ~ operator is a bit inverse, so ~0 gives you an integer value with all ones (in binary).

like image 44
payne Avatar answered Dec 06 '22 16:12

payne