Arthur Collé
Arthur Collé

Reputation: 2607

For loop without the second condition, i.e. the boolean check?

I have to write a function that calculates the floor of log base 16 of an unsigned int passed in. There are restrictions as to what operators and what constants we are allowed to use, and we can only use specifically for loops.

For clarity, we cannot use any conditional statements(if, else, switch ... ). The function prototype is:

int floor_log16(unsigned int x); 

Allowed operators: ++ -- = & | ~ ^ << ! >>

Allowed constants: 1 2 3 4 8 16

I wrote a version of the program as follows:

int floor_log16(unsigned int x) {
    int index=1;
    int count=(1!=1);

    count--;

    for(; index<=x; index<<=4) {
        count++;
    }

    return count;
}

which seems to work as desired. However, I realized that based on the later functions and description of the needed functionality we have to write, I noticed that under "allowed operators" sometimes > and < were listed.

I deduce this implies that since for the floor_log16 function listed above, we weren't explicitly told to use > or <, I can only assume that the solution posted above will not be accepted.

This leaves me rather confused because I don't understand how you can possibly have a for loop without a boolean check?

Isn't the whole idea of a loop to iterate while a condition is met?

Upvotes: 6

Views: 8366

Answers (3)

1&#39;&#39;
1&#39;&#39;

Reputation: 27115

If you XOR any unsigned with itself, it becomes 0. So int count=(1!=1); could be changed to int count = 1 ^ 1.

As for the loop condition, Roman's idea of comparison to 0 seems like the most natural way to go.

Upvotes: 0

Roman Nikitchenko
Roman Nikitchenko

Reputation: 13046

I don't like to spoil your task but consider about for condition like 'comparison to 0'. This doesn't require any explicit operator. One of possible way to get it is something like this:

// This cycle will end as soon as index is 0.
for (;index; index = (index >> 4))
{
    // ...
}

Upvotes: 2

kirelagin
kirelagin

Reputation: 13616

Well, first of all, for-loop without the boolean check is perfectly fine. For example,

for (;;)

is a common way of writing

while (true)

Second, having a for-loop with other parts but without boolean check is still useful as you can exit it with return or break.

And the last thing. There are tons of ways of getting a boolean without using < and >. For example, you can simply use i to check that i != 0 and so on.

For example if you want to check that a < b you can check for (a - b) < 0 instead. Implementing addition (and hence subtraction) with bitwise operators is a well known interview question (you should really try to do this yourself, it's fun), and checking that your int is negative is as easy as looking at its most significant bit.

Upvotes: 5

Related Questions