This question is inspired by this question, which features the following code snippet.
int s;
if((s = foo()) == ERROR)
print_error();
I find this style hard to read and prone to error (as the original question demonstrates — it was prompted by missing parentheses around the assignment). I would instead write the following, which is actually shorter in terms of characters.
int s = foo();
if(s == ERROR)
print_error();
This is not the first time I’ve seen this idiom though, and I’m guessing there are reasons (perhaps historical) for it being so often used. What are those reasons?
When you are writing a loop, it is sometimes desirable to use the first form, as in this famous example from K&R:
There is no elegant “second-form” way of writing this without a repetition:
Or:
Now that the assignment to
cis repeated, the code is more error-prone, because one has to keep both the statements in sync.So one has to be able to learn to read and write the first form easily. And given that, it seems logical to use the same form in
ifconditions as well.I tend to use the first form mostly because I find it easy to read—as someone else said, it couples the function call and the return value test much more closely.