-6

I am new to programming, and can not understand how the following code is interpreted by the compiler. As you can notice in the code, the while loop does not have curly braces around the code that comes right after it. Can somebody please explain to me, step by step, how this loop works:

int num = 0;
while(++num < 6) 

    Console.WriteLine(++num);
    Console.WriteLine(num++);
    Console.WriteLine(++num);
PiJei
  • 584
  • 4
  • 19
Gama47
  • 1
  • 1

2 Answers2

4

A while loop without braces is the same as a while loop with braces surrounding the line immediately below it:

int num = 0;
while(++num < 6) 
{
    Console.WriteLine(++num);
}
Console.WriteLine(num++);
Console.WriteLine(++num);

First iteration:

while(1 < 6) // num is 1
{
    Console.WriteLine(2); // num is 2
}

Second iteration:

while(3 < 6) // num is 3
{
    Console.WriteLine(4); // num is 4
}

Third iteration:

while(5 < 6) // num is 5
{
    Console.WriteLine(6); // num is 6
}

On the fourth iteration, num becomes 7 and then gets checked by < 6, which evaluates to false. The while loop exits and the two lines below gets executed.

// num is 7
Console.WriteLine(7); // num is 8
Console.WriteLine(9); // num is 9

So it prints 2, 4, 6, 7, 9

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Since ommitting curly braces can quickly lead to unexpected behavior or hard to read code, it is good practice to always write them, even if not needed. Consider the following code (I have left out the indentation on purpose):

int i, j;
for (i=0;i<10;i++)
for (j=0;j<10;j++)
if (j > i)
continue;
foo(i, j);

Nobody will be able to read that, and even if you add the spaces, it's very error prone. Also, if you later need to add another line to the if () condition, you'll very likely forget to also add braces. (The example is very poor: foo(i,j) will only be called once and the loop will do nothing!)

Also beware of the following slightly modfied code from your question:

int num = 0;
while(++num < 6); // Careful: a semicolon ends the statement
Console.WriteLine(++num);

This will run the loop six times before even calling Console.WriteLine once, because the semicolon ends the statement.

PMF
  • 14,535
  • 3
  • 23
  • 49
  • Thank you!! I know its bad not using curly braces, im just playing with the code so i can understand how it all works, Thanks again – Gama47 Aug 27 '18 at 19:08