as3rdaccount
as3rdaccount

Reputation: 3951

what does the following C code translate to?

So I have a for loop which goes like this:

for(span=N>>1;span;span>>=1)

I am assuming the start and end conditions are equivalent to as follows:

span = N>>1; //right shift N by 1 and initialize to span
while(span!=0)
{
 span = span >> 1;
}

However it seems a little bizarre in the context of my code. Thanks in advance!

Upvotes: 0

Views: 87

Answers (3)

Abhineet
Abhineet

Reputation: 5399

Short and sweet...Yes as far as you have shown the code, your interpretation stands firm and good.

Upvotes: 0

lc.
lc.

Reputation: 116528

That is correct.

  • The initializer sets span = N >> 1, right-shifting N by 1.
  • The loop condition is span, which is equivalent to span != 0.
  • Every time the loop comes around, span is right-shifted again by 1.

In the context of positive integers, this is equivalent to for(span=N/2;span>0;span/=2). However, without knowing your particular context I cannot comment whether this is or is not bizarre.

Upvotes: 0

hjindal
hjindal

Reputation: 616

In every iteration you are dividing the variable span by 2 until it reaches 0.

so if initially N = 8, then values for span will be 4, 2, 1, 0 -> exit loop

Upvotes: 4

Related Questions