-2

I'm going through a book at the moment (C# 8.0 and .NET Core 3.0) and I'm stuck with understanding / Googling the explanation for this question.

Does the following statement compile? for ( ; true; ) ;

I chucked the code in my editor and it does compile, but any code below is unreachable (which is fine). I'm hoping someone can explain what this statement is doing.

Cheers

Leslie Alldridge
  • 1,427
  • 1
  • 10
  • 26
  • 1
    `const bool ever = true; for (;ever;){/*...*/}` Edit: just rehashing good old [for ever macro](https://stackoverflow.com/a/652802/402022) for c# – Theraot Nov 01 '20 at 02:44
  • Oh nice it makes sense now after the edit :) edit: lol that link is a good read! – Leslie Alldridge Nov 01 '20 at 02:45
  • Oh I'm pretty sure I've figured it out now. I've never seen such an empty for loop before.. didn't realise you could write one up without having an assignment like `int i = 0` and without an increment/decrement like `i++`. The number of `;`'s threw me off at first. – Leslie Alldridge Nov 01 '20 at 02:39

1 Answers1

4

In all variants of C a for is comprised of three parts: initialization, condition and update.

Initialization is executed once when the for is initialized, for example declaring or updating a variable: for(int a = 0;//...

Afther that comes the condition that is checked on each loop, for example: a < 10; //..

And finally we have the update, something that will be executed after each loop: a++)

It's not mandatory to set any of these, you can even do for( ; ; ) ;, that would create an infinite loop.

So, the code you have will create a for that will check if true is true creating an infinite loop.

Gusman
  • 14,905
  • 2
  • 34
  • 50
  • 1
    Legend, thanks I'll accept as answer when the timer lets me. I figured it out at the same time but your explanation is much clearer! – Leslie Alldridge Nov 01 '20 at 02:40