Alex Rivera | Logout

What are the advantages of squashing assignment and error checking in one line?

Asked 2010-05-23T13:50:25.813
19

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?

Edit
Report

2 Answers

1

I personally prefer for assignments and tests to be on different lines. It is less syntactically complicated, less error prone, and more easily understood. It also allows the compiler to give you more precise error/warning locations and often makes debugging easier.

It also allows me to more easily do things like:

int rc = function();

DEBUG_PRINT(rc);

if (rc == ERROR) {
    recover_from_error();
} else {
    keep_on_going(rc);
}

I prefer this style so much that in the case of loops I would rather:

while (1) {
    int rc = function();
    if (rc == ERROR) {
        break;
    }
    keep_on_going(rc);
}

than do the assignment in the while conditional. I really don't like for my tests to have side-effects.

answered 2010-05-23T21:06:31.803
0

I often prefer the first form. I couldn't say exactly why, but it has something to do with the semantic involved.

The second style feels to me more like 2 separate operations. Call the function and then do something with the result, 2 different things. In the first style it's one logical unit. Call the function, save the temprary result and eventually handle the error case.

I know it's pretty vague and far from being completely rational, so I will use one or the other depending on the importance of the saved variable or the test case.

answered 2010-05-23T14:21:56.123

Your Answer