0

Hey guys i stumble upon a code online which was written in C language and while reading the codes i saw the for loop did not have initialization,condition nor the increment. The loop looked like this.

for (;;)
{
    bool main_flag = false;
    while (main_flag == false)
    {
        displayMainMenu();
        switch (main_input)
        {
        case 1: addCar(head, tail); main_flag = true; break;
        case 2: removeCar(head, tail); main_flag = true; break;
        case 3: display(head, tail); main_flag = true; break;
        case 4: printf("Terminating..."); return 0;
        default: printf("\nINVALID INPUT!\nTRYAGAIN !\n");

        }
    }
}

Anyone able to explain to me what kind of for loop is that and how does it work? thanks alot

Dexter Siah
  • 273
  • 2
  • 6
  • 17

1 Answers1

2

It is exactly doing what it implies: There is no condition to stop the loop, hence it is actually an endless loop.

So

for(;;) {}

is essentially the same as

while(true) {}

The only way to get out of the loop is to use a break or a return.

Lukas
  • 1,320
  • 12
  • 20
  • or `exit`͏͏͏͏͏͏͏͏͏͏͏͏ – Bathsheba Jul 06 '18 at 13:15
  • @Bathsheba -- or segfault ;) – ad absurdum Jul 06 '18 at 13:16
  • @DavidBowling: Strictly that's a manifestation of UB. Not sure we can really count that one. – Bathsheba Jul 06 '18 at 13:17
  • hmm now that u mentioned does make sense... alright thanks – Dexter Siah Jul 06 '18 at 13:18
  • 1
    And the reason you may see `for(;;)` instead of `while(true)` is that the former is, when viewed from a certain perspective, more efficient than the latter, because the former just loops while technically the latter must check the truth value each iteration to determine whether to keep looping. But practically speaking the compiler will almost certainly treat them exactly the same. – Andrew Cottrell Jul 06 '18 at 18:15