The C++ while Statement

The while statement executes a statement repeatedly until the termination condition (the expression) specified evaluates to zero. The test of the termination condition takes place before each execution of the loop; therefore, a while loop executes zero or more times, depending on the value of the termination expression. The following code uses a while loop to trim trailing spaces from a string:

char *trim( char *szSource )
{
    char *pszEOS;

    // Set pointer to end of string to point to the character just
    //  before the 0 at the end of the string.
    pszEOS = szSource + strlen( szSource ) - 1;

    while( pszEOS >= szSource && *pszEOS == ' ' )
        *pszEOS-- = '\0';

    return szSource;
}

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

The expression must be of an integral type, a pointer type, or a class type with an unambiguous conversion to an integral or pointer type.