jimmythefloyd Posted April 24, 2011 Posted April 24, 2011 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(); Quote
Leaders snarfblam Posted April 25, 2011 Leaders Posted April 25, 2011 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] } Quote [sIGPIC]e[/sIGPIC]
cloudmonkey Posted July 21, 2011 Posted July 21, 2011 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. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.