Will this for a loop run indefinitely?
I have some experience with c programming, but sometimes the author of some books just asks such a strange syntax question that we will never use in real programming and is similar to the one I have stuck with one such question, although the answer is given, but I am unable to understand the answer ... Here is the code below
int main
{
int i;
for(;scanf("%d",&i);printf("%d",i)){
;
}
}
The question is how many times this will run for a loop and the answer provided is undefined Can someone please explain how the loop will be executed.
source to share
Here indefinite means it cannot be determined (unknown), it doesn't mean infinity (just to clear things up). Because here, the number of times the loop runs depends on the input you entered. If a valid input is given, which is an integer, the loop continues. If an invalid input is given, that is, not an integer, the control jumps out of the loop. So you don't have a single answer for all scenarios, so it's vague.
source to share
Not. This is not an endless cycle for
.
According to loop syntax for
from section 6.8.5.3 n1256 TC3 C99
for ( clause-1; expression-2; expression-3 )
behaves as follows: expression-2 is a control expression that is evaluated before each execution of the loop body ....
In your case expression-2 is equal scanf("%d",&i)
and the return value will be considered to evaluate expression-2 scanf()
.
According to the man page scanf()
Return value
... return the number of input items successfully matched and assigned, which may be less than envisaged, or even zero in the event of an early mismatch.
So in your case
-
until the point in time
scanf()
it is a success, it will benumber of input items successfully matched
that matters1
and theTRUE
loopfor
will continue executing. -
if
scanf()
[example: enterchar
value] does not work , the return valuescanf()
will be0
[match failure] and the loop will end.
source to share
After accepting the answer
Yes, it can very well be an endless loop.
scanf()
returns the number of fields successfully scanned (0 or 1) here or EOF
on I / O error or end of file.
The only way to exit the loop is to enter a non-numeric input like "xyz".
If the user has closed stdin
, scanf()
will return EOF
. EOF
- negative value (not 0). So the loop will keep calling scanf()
, keep getting EOF
, until the program is killed.
#include <stdio.h>
int main(void) {
int i;
for (; scanf("%d", &i); printf("%d", i)) {
;
}
return 0;
}
source to share