[英]C# while loops and semi colons
我正在运行一个代码,如果我这样写:
int num = 0;
while (num++ < 6) ;
{
Console.WriteLine(num);
}
我得到一个 7 的 output
但如果它是这样写的
int num = 0;
while (num++ < 6)
{
Console.WriteLine(num);
}
我得到一个 1,2,3,4,5,6 的 output
我真的很困惑为什么仅仅通过添加一个额外的分号来输出如此不同。我明白为什么它是顶部代码的 7,但为什么它不显示所有答案的循环?
如果有人能解释一下,真的很感激:)谢谢
分号表示整个 while 循环就是那一行——这意味着之后的 {} 块不是循环的一部分——而是接下来发生的事情。
所以这:
int num = 0;
while (num++ < 6) ;
{
Console.WriteLine(num);
}
和写法一样:
int num = 0;
while (num++ < 6)
{
}
Console.WriteLine(num);
看到不同?
调试代码时,您会看到:
int num = 0;
while (num++ < 6) ; //It checks until num>6 (6 times)
{ //without running the code inside the Curly Brackets
Console.WriteLine(num); // Then it runs just once this line
}
那是因为分号
对于第二个选项
int num = 0;
while (num++ < 6) // it checks the condition every time
{
Console.WriteLine(num); // it runs this line of code 6 times
}
我在大学做一些课程工作时遇到了这个问题,并且从未忘记这一点。 基本上你是用分号终止while循环而不运行里面的代码。 然后编译器会删除大括号,最终得到:
int num = 0;
while (num++ < 6) {}
Console.WriteLine(num);
问题是这很难找到,如果此代码投入生产,可能会导致重大错误。 TBH 我不确定为什么编译器允许这样做或它有什么用处!
int num = 0; // num is 0
while (num++ < 6) ; // the ; makes this "function" repeat until 6 is reached
{ // since function above has ; this { does nothing
Console.WriteLine(num); // prints where num stopped at, which is 6
} // since function above has ; this } does nothing
=====================================================================================
/* This function is the same as... */
int num = 0;
while (num++ < 6)
{
DoNothing();
}
Console.WriteLine(num);
int num = 0; // num is 0
while (num++ < 6) // no ; makes this "function" do num++ then continue
{ // { start of the instructions
Console.WriteLine(num); // prints where num stopped at, first round is 1
} // end of the instructions
// will go back to while loop until num reaches 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.