3
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?

wallyk
  • 56,922
  • 16
  • 83
  • 148
Nigel
  • 161
  • 12

1 Answers1

7
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. i.e. this is whether this is 0 or non 0 Non zero can take any value e.g. 5, 10, -5 etc.

So, if you apply !0 you get the value of 1. For any other value e.g. !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)

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • in this line !arr[i - 1], so the ! operator will turn the result to 1 if arr[i-1] ==0? could you please elaborate a bit more? – Nigel Sep 19 '19 at 06:27