Answer the question
In order to leave comments, you need to log in
Implementing a final loop without checking the exit condition?
Good afternoon. The question is purely academic, but it haunts me.
I came across a dispute about whether it is possible to implement the final loop so that there is not a single condition check in the compiled code.
It seems like, as a result, the following example (C ++) was born. Approximately how it works, I understood, but a lot of incomprehensible.
Can someone explain what exactly is going on in this line:
void (*ptr)(int) =(void (*)(int)) ((int)CycleIteration + (arg / N) * ((int)CycleEnd - (int)CycleIteration));
#include <stdio.h>
#include <stdlib.h>
int N = 0;
void CycleEnd(int arg)
{
printf("cycle is finished, N = %d ", arg);
}
void CycleIteration(int arg)
{
printf("%d\n", arg);
void (*ptr)(int) =(void (*)(int)) ((int)CycleIteration + (arg / N) * ((int)CycleEnd - (int)CycleIteration));
ptr(arg + 1);
}
void cycleBegin(int iteratorStartValue, int iteratorEndValue)
{
N = iteratorEndValue - 1;
CycleIteration(iteratorStartValue);
}
int main()
{
cycleBegin(0, 100);
}
Answer the question
In order to leave comments, you need to log in
The main feature is that. that arg / N == 0 as long as arg < N.
The iterator function calls the ptr function at the address.
The address is calculated by the formula "address of the iterator function plus the very expression arg / N multiplied by the difference between the addresses of the iterator function and the end of the loop function.
Instead of a banal comparison, a mathematical expression is used, that's the whole trick.
And yes, Antony is right - this is not
PS By the way, you can turn this perversion into a cycle - create a vector of function addresses, fill it with the required number of addresses of the function that changes the loop variable, and add the address of the final function to the end . ... but without recursion ;))
PPS Although the vector is also not needed here. Just an array of two values and an index - that's the same expression.
There was something like this recently on Habré . Loop from 100 to 0 with output values but no conditional statements. There were several options in the comments. I liked the highlighting implementation the most by hosting new[] and a static variable in the class in this comment the best .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question