I am checking a condition inside a loop, and if it holds, do something.
for (i = 0; i < n; i++)
{
// do lots of work here
.
.
.
if (constant_condition)
do_something(n);
}
The condition is independent of n, so it feels redundant to check it every time. I could instead do this:
if (constant_condition)
for (i = 0; i < n; i++)
{
// do lots of work here
.
.
.
do_something(n);
}
else
for (i = 0; i < n; i++)
{
// do lots of work here
.
.
.
}
This new code is more efficient, but I had to copy paste the same code in my program. Is there an efficient way to do this without repeating the same block of code?
Edit: the condition is not known at compile time, but it will be given at runtime and will not change.