0

Example :

void top(int *a, int *b)
 {
     L1 : for (int i = 0; i < *a; i++)
     {
         for (int j = 0; j < 5; j++)
         {
             *b += *a;
         }
     }
  }

Can I call the above nested loop L1 as perfect loop nest? A perfect loop nest should have constant bounds. I'm unclear if this situation comes into constant loop bound scenario.

  • 2
    From [what-is-the-difference-between-perfectly-nested-loop-and-imperfectly-nested-loop](https://stackoverflow.com/questions/24749801/what-is-the-difference-between-perfectly-nested-loop-and-imperfectly-nested-loop), *"A perfectly nested loop is one wherein all content is in the innermost loop"*. It is the case here. – Jarod42 Jun 22 '23 at 09:00
  • 1
    Well, the label isn't in the inner loop... and should be removed since goto is considered harmful. – Lundin Jun 22 '23 at 09:23
  • @Lundin: more to the point, the label is unused, so it should be removed. – Jonathan Leffler Jun 22 '23 at 15:28

1 Answers1

0

Since the only statement in the body of the outer loop is the inner for loop, this nested for loop is a perfectly nested loop.

Note that neither gcc nor clang optimize the posted code beyond simple unrolling of the inner loop.

I wonder what compiler can reduce the code down to:

void top(int *a, int *b) {
    if (*a > 0)
        *b += *a * *a * 5;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Your "optimized" code is not correct if a and b point to the same int. – gerum Jun 22 '23 at 10:40
  • 1
    @gerum: that's true and it might explain the *limited* optimisation. Yet if `a` and `b` point to the same strictly positive `int`, running the function will keep increasing that until arithmetic overflow causes undefined behavior, so my version is just as good in this case :) – chqrlie Jun 22 '23 at 13:30