Opened 2 days ago

#290 new defect

Two-Argument Conditional Revaluates Condition

Reported by: ajbeach Owned by:
Priority: major Component: cfa-cc
Version: 1.0 Keywords:
Cc:

Description

The two-argument conditional currently is implemented as a short hand and evaluates its condition twice instead of once. For example the following piece of code prints "yes" twice instead of once:

bool yes() {
    printf("yes\n");
    return true;
}

int main(int argc, char * argv[]) {
    bool result = yes() ?: false;
    printf("result: %s\n", result ? "true" : "false");
}

This is because, under the hood we copy the entire expression instead of using the result of one expression twice. To write it out in code:

condExpr ?: elseExpr
// Is treated as:
condExpr ? condExpr : elseExpr
// Should be treated as:
({ TYPE NAME = condExpr; NAME ? NAME : elseExpr; })

(Where TYPE and NAME are found internally, if they explicitly exist at all.) This will probably require some resolver trickery as the expression must be resolved so it can be used as both the condition-expression and then-expression.

It is also theoretically possible to construct a case where one of the condition and then-expression are resolved differently than the expression that should be used in both locations. Or even both. I haven't constructed such a case and expect it is extremely rare in practice.

Change History (0)

Note: See TracTickets for help on using tickets.