Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...