3 ms·
> Nesting the same function call in both branches of if/else unintentionally obscures that it's not a conditional printf call. And the version with mutation ma
by nybble41 5y ago
> Nesting the same function call in both branches of if/else unintentionally obscures that it's not a conditional printf call.
And the version with mutation masks the fact that the initial value assigned to `ret` may or may not be used, which seems like a very similar problem to me. Plus it involves mutation, which IMHO significantly increases the complexity of any code. Unfortunately C offers limited options here; as cryptic and controversial as it may be, the ternary operator is the only (non-hackish) way to make an expression which selects between two or more values based on a boolean condition without either the possibility of failing to assign a value or requiring a "default" value which at least some paths through the function won't use. (What if there is no reasonable default value and all the required branches are expensive to compute?)
> If you're going to write: … printf(a == b ? "equal" : "not"); … you don't need the function at all, completely missing the point.
The function still encapsulates the specific comparison and the way the result is reported—exactly like the other versions—so I wouldn't say it's completely useless despite containing only one line of code. This is, of course, merely a toy example. You could assign the string to a named const variable if you wanted to make it slightly more self-documenting, though I question whether that would make this particular code any more readable.