4 ms·
IMHO the original version without the mutable local variable was much more obvious. In any language. Though I would also accept: void fn(int const a, int co
by nybble41 5y ago
IMHO the original version without the mutable local variable was much more obvious. In any language.
Though I would also accept:
void fn(int const a, int const b)
{
printf(a == b ? "equal" : "not");
}
to avoid duplicating the call to printf(). If this were Rust I might suggest:
fn theFn(a: isize, b: isize)
{
let ret;
if a == b {
ret = "equal";
} else {
ret = "not";
}
println!("{}", ret);
}
but only because Rust, unlike C or C++, will enforce that `ret` is assigned exactly once before it is used.
- Supermancho 5y ago> IMHO the original version without the mutable local variable was much more obvious. In any language. This is not about obviousness. You can write the same expression lots of different ways, which are all obvious. This is still a question about testable paths and code hygiene. Nesting the same function call in both branches of if/else unintentionally obscures that it's not a conditional printf call. If you're going to write: printf(a == b ? "equal" : "not"); you don't need the function at all, completely missing the point. Your second example is definitely better in Rust.
- 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.