I’m quite familiar with using short-circuit evaluation as an inline if, and my understanding was that writing cond && (expression)
is exactly identical to the more traditional:
if cond
expression;
end
However, I found a case where this leads to unexpected behavior. I needed to find the minimum and maximum of each sub-list of a list of lists T
, element-wise (among other things). So I wrote something in the same spirit of the following:
T = [[1,2],[0,1],[1,-1]];
limits = [Inf,-Inf,Inf,-Inf];
cond = true;
for t in T
for i in eachindex(t)
if cond
limits[2*i-1:2*i] .= min(limits[2*i-1],t[i]), max(limits[2*i],t[i]);
end
end
end
Here the behavior is as expected, with limits = [0.0,1.0,-1.0,2.0]
. However, if I substitute the if in the middle with:
cond && ( limits[2*i-1:2*i] .= min(limits[2*i-1],t[i]), max(limits[2*i],t[i]) )
I obtain limits = [0.0,0.0,-1.0,-1.0]
!
Why is this the case? By trial-and-error, I found that putting additional parentheses around min
and max
fixes the issues, but this unexpected result makes me wary of using short-circuit evaluation so freely. Does anybody have any idea?