简体   繁体   中英

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.

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

~i is bitwise NOT operator. Ie 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM