What is the advantage of commas in a conditional statement?

后端 未结 7 1725
醉酒成梦
醉酒成梦 2021-02-03 17:25

We can write an if statement as

if (a == 5, b == 6, ... , thisMustBeTrue)

and only the last condition should be satisfiable to ent

7条回答
  •  醉话见心
    2021-02-03 17:36

    What follows is a bit of a stretch, depending on how devious you might wish to be.

    Consider the situation where a function returns a value by modifying a parameter passed by reference or via a pointer (maybe from a badly designed library, or to ensure that this value is not ignored by not being assigned after returning, whatever).

    void calculateValue(FooType &result) {/*...*/}
    

    Then how do you use conditional statements that depend on result?

    You could declare the variable that will be modified, then check it with an if:

    FooType result;
    calculateValue(result);
    if (result.isBared()) {
        //...
    }
    

    This could be shortened to

    FooType result;
    if (calculateValue(result) , result.isBared()) {
        //...
    }
    

    Which is not really worth while. However, for while loops there could be some small advantages. If calculateValue should/can be called until the result is no longer bar'd, we'd have something like:

    FooType result;
    calculateValue(result);  //[1] Duplicated code, see [2]
    while (result.isBared()) {
        //... possibly many lines
        //separating the two places where result is modified and tested
    
        //How do you prevent someone coming after you and adds a `continue`
        //here which prevents result to be updated in the and of the loop?
    
        calculateValue(result); //[2] Duplicated code, see [1]
    }
    

    and could be condensed to:

    FooType result;
    while (calculateValue(result) , result.isBared()) {
        //all your (possibly numerous) code lines go here
    }
    

    This way the code to update result is in only one place, and is near the line where its conditions are checked.

    maybe unrelated: Another reason why variables could be updated via parameter passing is that the function needs to return the error code in addition to modify/return the calculated value. In this case:

    ErrorType fallibleCalculation(FooType &result) {/*...*/}
    

    then

    FooType result;
    ErrorType error;
    
    while (error = fallibleCalculation(result) , (Success==error && result.isBared())) {
        //...
    }
    

    but as noted in the comments, you can do this without the comma too:

    FooType result;
    ErrorType error;
    
    while (Success == fallibleCalculation(result) && result.isBared()) {
        //...
    }
    

提交回复
热议问题