ARM Technical Support Knowledge Articles

WHILE STATEMENT

Applies to: C Programming Language

Answer


Information in this article applies to:


QUESTION

How does the while C statement work?

ANSWER

The 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
");
}

This function prints "Hello world" forever (or at least until execution of the program is somehow stopped).

Article last edited on: 2004-06-28 11:34:51

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential