Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ~i really equivalent to i != -1?

How does ~i work in C++?

I just noticed it is equivalent to i != -1, but I'm not certain about that.

int arr[3] {1, 2, 3};
int n = 3;
for (int i = n - 1; ~i; i--) {
    cout << arr[i] << ' ';
}

It printed the array in reverse.

like image 820
Hossam Kamil Avatar asked Jun 26 '19 12:06

Hossam Kamil


2 Answers

~ is the bitwise NOT operator. ~i is 0 if and only if i has 1 in all its bits. Whether -1 has all bits 1 depends on how signed numbers are represented on the system. In two's complement representation, -1 is represented with all bits 1, so on such systems ~(-1) == 0. Neither in one's complement, nor in sign-and-magnitude does that hold true.

Therefore, the answer is no; not on all systems. That said, two's complement is fairly ubiquitous in modern machines (everything made since the 90's), and on such systems, the answer is yes. Regardless of the sign representation however, i != -1 is much more readable.

like image 51
eerorika Avatar answered Nov 19 '22 08:11

eerorika


~i is bitwise NOT operator. I.e. it inverts every bit in i. -1 is represented binary as every bit of number being set to 1, inverting every bit to 0 gets you 0. And when checking integer in place where bool is expected 0 is treated as false and any other number as true.

So, in this particular case yes, ~i is equivalent with i != -1.

like image 39
sklott Avatar answered Nov 19 '22 10:11

sklott