Warning
After looking over your code a second time, I must say, it may compile just fine, but you are going to encounter a deadlock, I do think:
for (i=1;i<=n;++i)
{
i = (i)&(i-1);
cont++;
}
What will happen? When i
is 1
:
i = 1&0;//is what line 4 boils down to
So i
will be 0
, if the loop started, then n
will be at least 1, so the loop condition still is true:
i<=n => 0 <= n ==> true
So i
is incremented by 1
(i++
), and the whole thing starts again. Line four, once again, evaluates to:
i = 1&0;//assigns 0 again to i
And you're back to square one. This program will never terminate, it'll simply repeat the same operation over and over and over...
Well, &
is the bitwise AND operator. It When used, as in your snippet with 2 integers, it returns the bits that are "switched on" or set to 1
in both numbers. In plain English: the expression evaluates to a new set of bits, which were set in both operands. Take, for example, when i
is 2:
00000010 //2
00000001 // i - 1
--------
00000000
In this case, non of the bits are set to 1
in both cases. As indeed this will be the fact for all powers of two, because the powers of 2 look like this in binary:
00000010
00000100
00001000
And a power of 2 minus 1 looks like this:
00001000//power of 2
00000111
In all other cases, there will, at least be 1 bit that is set to 1
in both cases:
00000110
00000101
--------
00000100
Easy.
For a more complete overview, and detailed explanation of bitwise operators in C, you can always refer to the wiki on bitwise operators in C