Although you can use any loop statement to create an infinite loop, for is traditionally
used for this purpose. Since none of the three expressions that form the for loop are
required, you can make an endless loop by leaving the conditional expression empty:
for( ; ; ) printf("This loop will run forever.\n");
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the
for(;;) construct to signify an infinite loop.
Actually, the for(;;) construct does not guarantee an infinite loop because a break
statement, encountered anywhere inside the body of a loop, causes immediate
termination. (break is discussed in detail later in this chapter.) Program control then
resumes at the code following the loop, as shown here:
ch = '\0';
for( ; ; ) {
ch = getchar(); /* get a character */
if(ch=='A') break; /* exit the loop */
}
printf("you typed an A");
This loop will run until the user types an A at the keyboard.
used for this purpose. Since none of the three expressions that form the for loop are
required, you can make an endless loop by leaving the conditional expression empty:
for( ; ; ) printf("This loop will run forever.\n");
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the
for(;;) construct to signify an infinite loop.
Actually, the for(;;) construct does not guarantee an infinite loop because a break
statement, encountered anywhere inside the body of a loop, causes immediate
termination. (break is discussed in detail later in this chapter.) Program control then
resumes at the code following the loop, as shown here:
ch = '\0';
for( ; ; ) {
ch = getchar(); /* get a character */
if(ch=='A') break; /* exit the loop */
}
printf("you typed an A");
This loop will run until the user types an A at the keyboard.
No comments:
Post a Comment