Search code examples
c++while-loopbooleanimplicit-conversionboolean-expression

What conversion happens when we use "while" in C++?


I'm using the Microsoft documentation and cppreference as background. Microsoft's site says that the expression to be evaluated in while must be an integral type, a pointer type or some conversible to these. Cppreference's site although says that while expects a bool type expression.

What does really happen? The expression will be converted to bool or not necessarly?If I use, for example, a char type expression inside a while, wont it be necessary to be converted to bool?


Solution

  • According for example to the C++ 14 Standard (6.4 Selection statements)

    2 The rules for conditions apply both to selection-statements and to the for and while statements

    1. ...The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed.

    Here is a demonstrative program.

    #include <iostream>
    
    struct A
    {
        operator int() const { return 1; };
    };
    
    int main() 
    {
        A a;
    
        while ( a ) break;
        
        return 0;
    }
    

    At first the object a is converted to the type int using the user defined conversion operator

    operator int() const { return 1; };
    

    After that there is applied the standard conversion from the type int to the type bool.

    From the C++ 14 Standard (4 Standard conversions)

    7 [ Note: For class types, user-defined conversions are considered as well; see 12.3. In general, an implicit conversion sequence (13.3.3.1) consists of a standard conversion sequence followed by a user-defined conversion followed by another standard conversion sequence. — end note ]