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
?
The
!
is the Logical Negation operator. It is not applied on a pointer as you mention, but on the valuearr[i-1]
. Ifarr[i-1] ==0
the result is1
otherwise the result is 0.~
is the Bitwise NOT operator It will invert all the binary bits ofsum
. It is sometimes also called the ones complementThe result of
~sum +1
is the same as taking the two's complement ofsum
, which is equal to the negative of sum. If sum is5
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
ornon 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