简体   繁体   English

为什么这是跳出 while 循环的有效 scanf 语句?

[英]Why is this a valid scanf statement to break out of a while loop?

Why is this a valid line of code to break out of an infinite while loop?为什么这是打破无限while循环的有效代码行?

if (scanf("%s", word) != 1) break;
if (scanf("%s", word) != 1) break;

scanf returns the number of items successfully consumed. scanf返回成功消费的项目数。 This value is used as the left hand operand inside of the expression.此值用作表达式内的左侧操作数。 Thus, this expression is perfectly valid.因此,这个表达式是完全有效的。

In the following example this value shall be 1 if no I/O error occurred and a string was successfully converted because there is only one item to consume.在下面的示例中,如果没有发生 I/O 错误并且成功转换了字符串,则该值应为1 ,因为只有一项要消耗。

I guess this if statement is part of a loop whose intention is to read subsequent words from the input until it encounters an EOF state for stdin or any redirected file used as input because the condition is only then evaluated to true (and with that to break out of the surrounding loop) if EOF or another I/O error has happen as scanf() returns 0 in this case.我猜这个if语句是一个循环的一部分,其目的是从输入中读取后续单词,直到它遇到一个EOF stdin用于标准输入或用作输入的任何重定向文件,因为只有然后条件才被评估为true (并且要打破如果发生EOF或其他I/O错误,因为scanf()在这种情况下返回0

This shall give you an insight of how this if statement is to be evaluated and interpreted.这将使您了解如何评估和解释这个if语句。

The mentioned break statement and its guard is valid but it's lying.提到的 break 语句及其保护是有效的,但它在撒谎。 Consider the loop考虑循环

while (1) {
   ...
}

According to the rules of structured programming the loop should never exit, that is unless the program exits.根据结构化编程的规则,循环不应该退出,除非程序退出。 Rather than using a break statement, a properly structured program should use the return value from the function scan as the loop guard, like this:而不是使用 break 语句,一个结构正确的程序应该使用 function扫描的返回值作为循环保护,如下所示:

tokenCount = scanf("%s", word);
while (tokenCount == 1) {
    ...
    tokenCount = scanf("%s", word);
}

It's also easier to reason about the correctness of a program if expressions do not have side effects;如果表达式没有副作用,也更容易推断程序的正确性; that's why the return value is stored in a variable (with a meaningful name).这就是为什么返回值存储在变量中(具有有意义的名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM