Why is this a valid line of code to break out of an infinite while
loop?
if (scanf("%s", word) != 1) break;
if (scanf("%s", word) != 1) break;
scanf
returns the number of items successfully consumed. 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 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.
This shall give you an insight of how this if
statement is to be evaluated and interpreted.
The mentioned break statement and its guard is valid but it's lying. 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:
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.