Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

How come I don't have to use a semicolon after the "i++" in the for loop, but if I were to write i++ after the console.writeline i would. Is it just just some kind quirky thing? or is there some deeper logic behind it.

    for (int i = 0; i < 12; i++ ) // doesn't need it, won't accept it here
           {
               Console.WriteLine(myClass.MethodA());
               i++;  // Would need semicolon here
           }
           
           Console.ReadLine();

  • Leaders
Posted
Is it just just some kind quirky thing?

The short answer is yes.

 

This syntax is inherited from C. It does seem inconsistent. However, consider the structure of the for statement (not sure if this is 100% technically correct, but it gets the idea across):

for ([i]statement[/i]; [i]expression[/i]; [i]expression[/i]) 
   [i]statement[/i]

Normally, a semi-colon denotes the end of a statement. As you can see, the last two are expressions. In this case, we are using the semi-colon as more of a delimiter. You don't normally write code with a trailing delimiter.

int x, y, z[color="Red"],[/color];

At the same time, C# does accept trailing commas in some cases. One reason for this is because it makes code generation simpler. (I use trailing commas in enums and initializers if they are declared across multiple lines.)

int[] x = {0, 1, 2, 3[color="Red"],[/color] };
var x = new { A = "Aye", B = "Bee"[color="Red"],[/color] };
enum x {a, b, c[color="Red"],[/color] }

[sIGPIC]e[/sIGPIC]
  • 2 months later...
Posted
How come I don't have to use a semicolon after the "i++" in the for loop, but if I were to write i++ after the console.writeline i would. Is it just just some kind quirky thing? or is there some deeper logic behind it.

    for (int i = 0; i < 12; i++ ) // doesn't need it, won't accept it here
           {
               Console.WriteLine(myClass.MethodA());
               i++;  // Would need semicolon here
           }
           
           Console.ReadLine();

 

The semi colon has always been used as a stopper at the end of a statement. A loop needs to be told to continue on, while a statement is the end of the line.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...