This is off-topic, but } else if (x + y > 20) {
is dead code x
and y
are both at most 10
so the sum will never be greater than 20
.
Personally I don’t feel like I often write very long chains of if-else, that is why I am fine with them adding a few indentation levels. If the chain is at the end of the function there is also no need for the surrounding scope.
Often times you also can use early exit instead of chains of if-else, I think the following should be recognizable by the compiler to be essentially the same?
(I don’t know, I haven’t done extensive comparisons of the resulting assembly, it is a genuine question)
const x : i8 = foo();
if (x < 0) {
// Print "x is too small."
return;
}
if (x > 10) {
// Print "x is too large."
return;
}
const y : i8 = bar();
if (y < 0) {
// Print "y is too small."
return;
}
if (y > 10) {
// Print "y is too large."
return;
}
if (x + y > 18) {
// Print "Sum of x and y is too large."
return;
}
// Print "x and y are ok."
return;
If there isn’t some big performance drawback to the early exit way I think I would prefer using that, in many situations.
If the program deals with error conditions, instead of printing stuff you might even change it to something like this:
const x : i8 = foo();
try checkRange(x, 0, 10, error.XTooSmall, error.XTooBig);
const y : i8 = bar();
try checkRange(y, 0, 10, error.YTooSmall, error.YTooBig);
if(x + y > 18) return error.SumTooBig;
return [_]i8{x, y};
Overall I think the only thing that would really convince me that this feature is a big benefit, was if there was a piece of code that would become way easier to write, that you can’t rewrite in a different style.
But using early exit instead, seems like it would be possible in most (or maybe even all) cases, and you also could use a scope and break from the scope instead, if you want to avoid the function for some reason.
I think that this is a nice to have syntax sugar, that isn’t really needed, because there are already other ways to do something that are similar enough. Because of that it may be against the "Only one obvious way to do things."
from the Zig zen. Although I wouldn’t say that it is obvious how to structure these if-else cases, I think it may be more obvious if we talked about real code instead of made up examples.