shaiko
Advanced Member level 5
- Joined
- Aug 20, 2011
- Messages
- 2,644
- Helped
- 303
- Reputation
- 608
- Reaction score
- 297
- Trophy points
- 1,363
- Activity points
- 18,302
Hello,
Taken from a programming book - this function is supposed to receive a 32 bit number and return the position of the 3rd bit that's a binary '1'.
A few questions:
1. The condition for exiting the for loop is i=32. On the other hand we have the return value statement:
if (count == 3)
return i;
So...when will the function exit? Will it loop over all 32 bits or will the
condition marked in red override this and cause the function to exit as soon as it's met?
2. What is the purpose of the "return -1" line ?
Taken from a programming book - this function is supposed to receive a 32 bit number and return the position of the 3rd bit that's a binary '1'.
Code:
int FindThird1(int reg)
{
int count = 0;
for (int i=0; i<32; i++)
{
count += (reg>>i)&1;
if (count == 3)
return i;
}
return -1;
}
A few questions:
1. The condition for exiting the for loop is i=32. On the other hand we have the return value statement:
if (count == 3)
return i;
So...when will the function exit? Will it loop over all 32 bits or will the
condition marked in red override this and cause the function to exit as soon as it's met?
2. What is the purpose of the "return -1" line ?