2 ms·
How does the 'else' confuse what is happening?
by throwawaylinux 5y ago
How does the 'else' confuse what is happening?
- Supermancho 5y agoThe function will perform a printf, so nesting it in an if-else subconsciously implies it's optional. This is a quirk of human text comprehension. In a small program, it seems arbitrary because you can see it all at once. Make the branches do more than simply printf and you can see why you want to frontload the else, rather than pick through the if/else to see what always happens.
- throwawaylinux 5y agoI can kind of see what you mean, but if you make branches do more then it's also quite possible the common actions become more tedious to factor into common code. And I don't think it's good practice to read control statements like that (obviously indented loops can't be assumed optional either). int pow2(int v, int pow) { int result; if (pow >= 0) result = v << pow; else result = v >> -pow; return result; } Looking at this, both sides of the if/else perform a multiply by 2^pow, you can't take the operation to possibly not happen. So I agree factoring common operations can be a good thing, but I think it's really a case by case basis and my code is fine. I would also caution against assuming something may not happen elsewhere in a function just because you see it inside a conditional block. This happens frequently to various degrees and I've never encountered a style policy preventing it or any compiler or linter warnings for it.