Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

while Statement (C++)

 

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

For the latest documentation on Visual Studio 2017, see while Statement (C++) on docs.microsoft.com. Executes statement repeatedly until expression evaluates to zero.

  
      while ( expression )  
   statement  

The test of expression takes place before each execution of the loop; therefore, a while loop executes zero or more times. expression must be of an integral type, a pointer type, or a class type with an unambiguous conversion to an integral or pointer type.

A while loop can also terminate when a break, goto, or return within the statement body is executed. Use continue to terminate the current iteration without exiting the while loop. continue passes control to the next iteration of the while loop.

The following code uses a while loop to trim trailing underscores from a string:

// while_statement.cpp  
  
#include <string.h>  
#include <stdio.h>  
char *trim( char *szSource )  
{  
    char *pszEOS = 0;  
  
    //  Set pointer to character before terminating NULL  
    pszEOS = szSource + strlen( szSource ) - 1;  
  
    //  iterate backwards until non '_' is found   
    while( (pszEOS >= szSource) && (*pszEOS == '_') )  
        *pszEOS-- = '\0';  
  
    return szSource;  
}  
int main()  
{  
    char szbuf[] = "12345_____";  
  
    printf_s("\nBefore trim: %s", szbuf);  
    printf_s("\nAfter trim: %s\n", trim(szbuf));  
}  

The termination condition is evaluated at the top of the loop. If there are no trailing underscores, the loop never executes.

Iteration Statements
Keywords
do-while Statement (C++)
for Statement (C++)
Range-based for Statement (C++)

Show:
© 2017 Microsoft