简体   繁体   中英

question about C pointer on boolean value,

int bar(int *arr, size_t n)
{
    int sum = 0, i;
    for (i = n; i > 0; i--)
    {
        sum += !arr[i - 1];
    }
    return ~sum + 1;
}

I have come across this code but don't quite understand sum +=;arr[i - 1]; : what is the effect of?(NOT) applied to the pointer of an array, Also, what is the effect of ~ before sum ?

sum += !arr[i - 1];

The ! is the Logical Negation operator. It is not applied on a pointer as you mention, but on the value arr[i-1] . If arr[i-1] ==0 the result is 1 otherwise the result is 0.

~sum + 1;

~ is the Bitwise NOT operator It will invert all the binary bits of sum . It is sometimes also called the ones complement

The result of ~sum +1 is the same as taking the two's complement of sum , which is equal to the negative of sum. If sum is 5 it will return -5

Some more explanation on the Logical Operators

When the Logical operators (Logical AND, OR, NOT) are applied on a variable, it only checks the logical state of the variable. ie this is whether this is 0 or non 0 Non zero can take any value eg 5, 10, -5 etc.

So, if you apply !0 you get the value of 1. For any other value eg !5 the answer is 0.

From C99 6.5.3.5

The result of the logical negation operator, is 0 if the value of its operand compares unequal to 0. 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E)

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