Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand the use of "while(true)" and "for(; ;)" loops in C#!

sample code for While(true) loop :

    public void HandleConnection()
    {
        TcpClient tcpClient = tcpListener.AcceptTcpClient();
        NetworkStream networkStream = tcpClient.GetStream();
        while (true)   /**Don't understand this while(true) loop**/
        {
            buffer = new byte[1024];
            n = networkStream.Read(buffer, 0, buffer.Length);
            if (n == 0)
            {
                break;
            }

        }
    }

Sample code for for(; ;) loop:

     public void readLine(NetworkStream inputStream)
     {
        using (StreamReader reader = new StreamReader(inputStream))
        {

            char[] buffer = new char[128];
            int n;

            for (; ; ) /**Don't understand this for(; ;) loop**/
            {
                n = reader.Read();
                if (n == -1 || n == '\n')
                {
                    break;
                }
        }
      }

Can anybody give a clear understanding of the above loop statements with reffering to the sample code provided? Thank you for your help!

like image 750
Xris Avatar asked Nov 29 '22 03:11

Xris


1 Answers

The first one should be easy:

while(true)

This just means that you should loop infinitely (unless there is some break inside the loop). It's meaning should be clear if you would just read it as a regular English line of text.

The other is a bit more tricky to explain:

for( ; ; )

Usually the part inside ( ... ) contains three statements: (1) a starting point, (2) an exit condition, (3) an increment. Without these three statements, it will just loop infinitely. Mainly because there is no exit-condition.

like image 82
Pieter Avatar answered Dec 06 '22 13:12

Pieter