[Rd] Documenting else's greed

Hugh Parsonage hugh@p@r@on@ge @end|ng |rom gm@||@com
Fri Aug 16 18:36:39 CEST 2019


I was initially pretty shocked by the result in this question:
https://stackoverflow.com/questions/57527434/when-do-i-need-parentheses-around-an-if-statement-to-control-the-sequence-of-a-f

Briefly, the following returns 0, not 3 as might be expected:

if (TRUE) {
    0
} else {
    2
} + 3

At first I thought it the question was simply one of syntax
precedence, but I believe the result is too surprising to not warrant
note in the documentation of Control. I believe the documentation
should highlight that the `alt.expr` is demarcated by a semicolon or
newline and the end of a *statement*, not a closing brace per se.

Perhaps in the paragraph starting 'Note that it is a common mistake to
forget to put braces...' it should end with. "Note too that it is the
end of a *statement*, not a closing brace per se, that determines
where `alt.expr` ends. Thus if (cond) {0} else {2} + 2 means if (cond)
{0} else {2 + 2} not {if (cond) {0} else {2}} + 2."



More information about the R-devel mailing list