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