| |||||
Technical Support Support Resources
Product Information | C: WHILE STATEMENTInformation in this article applies to:
QUESTIONHow does the while C statement work? ANSWERThe C while statement creates a structured loop that executes as long as a specified condition is true at the start of each pass through the loop. The while statement is created as follows: while (cond_exp) loop_body_statement where: cond_exp is an expression that is evaluated before each pass through the loop. If the value of the expression is "false" (i.e., compares equal to zero) the loop is exited. loop_body_statement is any valid C statement or block. Since cond_expr is checked before every pass through the loop, including the initial pass, it is possible to exit the loop without ever executing loop_body_statement. The following C statements can alter the flow of control in a while statement:
Examples
#include <stdio.h>
void
repeat_char(
int n,
char ch)
{
while (n--)
putchar(ch);
}
This function outputs n copies of the character ch.
#include <stdio.h>
char * get_string(void);
void process_string(char *s);
void func (void)
{
char *string;
while ((string = get_string()) != NULL)
process_string(string);
}
The while loop in func() gets strings by calling get_string() and processes them by calling process_string(). It stops as soon as get_string() returns a NULL pointer.
#include <stdio.h>
void prattle (void)
{
while (1)
printf("Hello world\n");
}
This function prints "Hello world" forever (or at least until execution of the program is somehow stopped). Last Reviewed: Monday, June 28, 2004 | ||||
| |||||