Reputation: 1023
(Sorry in advance, this question is probably very simple. I write code as a hobby and am just trying to wrap my mind around some things right now.)
I recently encountered a loop statement like (n
is a previously set positive integer):
int cnt;
for(cnt=0; n; cnt++){
n &= n - 1;
}
If I understand correctly, the middle entry in a loop should be a condition, but n;
does not seem to be a condition at all. Unless if it is understood as a bool (true
if n!=0
and false
if n==0
). If this is the correct way to think about it, would the following code be perfectly equivalent to the above?
int cnt=0;
while(n>0){
n &= n - 1;
cnt++;
}
If yes, why would one choose the former style of writing this instead of the while loop? It seems to me that a while loop would be the most clear and intuitive choice here, so I wonder if there is any advantage in the for loop that I missed? Thanks for any suggestion!
Upvotes: 3
Views: 167
Reputation: 385144
If I understand correctly, the middle entry in a loop should be a condition, but n; does not seem to be a condition at all.
It is.
Unless if it is understood as a bool (true if n!=0 and false if n==0).
Yes.
If this is the correct way to think about it, would the following code be perfectly equivalent to the above?
Nearly; it's n != 0
, not n > 0
.
If yes, why would one choose the former style of writing this instead of the while loop?
People do silly things all the time, for all sorts of reasons!
It seems to me that a while loop would be the most clear and intuitive choice here
I agree.
I wonder if there is any advantage in the for loop that I missed?
Nope.
Well, not for this one. If the loop body were different, say with more complex logic and a continue
statement or two, the behaviour of the program might be different (if you forgot to increment cnt
on your new code path). But that's not the case here.
Upvotes: 7