Hossam Kamil
Hossam Kamil

Reputation: 73

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.

Upvotes: 7

Views: 431

Answers (3)

Boki
Boki

Reputation: 657

Because your i variable from for loop is of type int, which is defined as signed integer, and as such in twos complement, its binary representation of value -1 is all bits set, what means all bits are 1. On other side, bitwise negation of all ones is all zeros, and that is what you need, loop to execute until i>=0 or i!=-1, since you decrementing i. In that context of bitwise operations on sign values on system has twos complement binary representation of int, yes, it is the same.

Upvotes: 0

eerorika
eerorika

Reputation: 238361

~ 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.

Upvotes: 14

sklott
sklott

Reputation: 2849

~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.

Upvotes: 5

Related Questions