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

I need to write a function that calculates the database floor 16 of an unsigned int passed to. There are restrictions as to which operators and which constants we are allowed to use, and we can only use for tags,

For clarity, we cannot use any conditional statements (if, else, switch ...). Function Prototype:

 int floor_log16(unsigned int x); 

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

Permitted constants: 1 2 3 4 8 16

I wrote the 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 later functions and a description of the necessary functionality, we should write, I noticed that under the "allowed operators" sometimes indicated > and < .

It follows that since the floor_log16 function mentioned above was not explicitly told to use > or < , I can only assume that the solution described above will not be accepted.

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

Isn't the whole idea of ​​the loop repeated until the condition is met?

+6
source share
3 answers

Well, firstly, for -loop without boolean checking is excellent. For instance,

 for (;;) 

- general recording method

 while (true) 

Secondly, having for -loop with other parts, but without a logical check, is still useful since you can exit it with return or break .

And the last one. There are several ways to get Boolean values ​​without using < and > . For example, you can simply use i to check that i != 0 , etc.

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

+5
source

I don’t like spoiling your task, but consider the for condition as "comparing with 0". This does not require an explicit statement. One possible way to get this is something like this:

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

If you XOR any unsigned with yourself, it becomes 0. Therefore, int count=(1!=1); can be changed to int count = 1 ^ 1 .

As for the loop condition, the idea of ​​comparing with 0 seems to be the most natural way.

0
source

Source: https://habr.com/ru/post/946869/


All Articles