Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"for (bool flag = true; flag; flag = false) { ... }" - is this normal?

Tags:

c#

for-loop

I've never seen a for loop initialized this way and don't understand why it would be written this way?

I'm doing some research into connecting to an IMAP server in .NET and started looking at code from a library named ImapX. I found the for loop in a method that writes data to a NetworkStream and then appears to read the response within the funky for loop. I don't want to copy and paste someone else's code verbatim, but here's the gist:

public bool SendData(string data)
{
  try
  {
    this.imapStreamWriter.Write(data);

    for (bool flag = true; flag; flag = false)
    {
      var s = this.imapStreamReader.ReadLine();
    }
  }
  catch (Exception)
  {
    return false;
  }

  return true;
}

Again, this isn't the exact code, but it's the general idea. That's all the method does, it doesn't use the server response, it just returns true if no exception was thrown. I just don't understand how or why the for loop is being used this way; can anyone explain what advantages initializing this offers, if any?

like image 625
sellmeadog Avatar asked Feb 21 '23 11:02

sellmeadog


1 Answers

It's a horrible way of executing a loop once. If you change the flag initalizer to something which isn't always true, it may have slightly more sense, but not a lot. I've entirely-unseriously suggested this code before now:

Animal animal = ...;
for (Dog dog = animal as Dog; dog != null; dog = null)
{
    // Use dog...
}

... as a way of using an as operator without "polluting" the outer scope. But it's language silliness, and not something I'd ever really use.

like image 184
Jon Skeet Avatar answered Mar 02 '23 01:03

Jon Skeet