Keil Logo

C: WHILE Statement

Information in this article applies to:

  • Keil MDK
  • C166 All Versions
  • C251 All Versions
  • C51 All Versions


How does the while C statement work?


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


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:

  • break
  • continue
  • goto
  • return


#include <stdio.h>

   int n,
   char ch)
   while (n--)

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)

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, December 7, 2020

Did this article provide the answer you needed?
Not Sure
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.