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

Posted by avakar on Stack Overflow See other posts from Stack Overflow or by avakar
Published on 2010-05-23T13:50:25Z Indexed on 2010/05/23 13:50 UTC
Read the original article Hit count: 162

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about c