In C++ what causes an assignment to evaluate as true or false when used in a control structure?

前端 未结 6 2009
后悔当初
后悔当初 2020-11-29 11:46

So can someone help me grasp all the (or most of the relevant) situations of an assignment inside something like an if(...) or while(...), etc?

What I mean is like:<

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 11:48

    if (a = b)
        ...
    

    is the shorthand for:

    a = b;
    if (a != 0)
        ...
    

    In a while statement, assignment within the condition enables the DRY principle:

    while (a = b)
    {
        ...
    }
    

    is shorthand for (notice how I had to replicate the assignment so that it is done right before the condition check):

    a = b;
    while (a != 0)
    {
        ...
        a = b;
    }
    

    That said, one classic issue with code like this is knowing whether the code intended to do an assignment or if the code forget an '=' when the intent was to write '==' (i.e. should that have been while (a == b).

    Because of this, you should never write just a plain assignment (gcc will issue a warning such as "suggest parentheses around assignment used as truth value"). If you want to use assignment in a control structure, you should always surround it with extra parentheses and explicitly add the not-equal:

    if ((a = b) != 0)
        ...
    
    while ((a = b) != 0)
        ...
    

提交回复
热议问题