Search code examples
cif-statementcoding-style

Assignment of a value, followed by comparison in "if" statement's condition in C


I want to write some code with the following logic. From a clarity and conciseness point of view, is the first approach better than the other two?

if(kErrNone != (cs_error = get_last_error(component)))
{
    /* Do something. */
}


if((cs_error = get_last_error(component)) != kErrNone)
{
    /* Do something. */
}


cs_error = get_last_error(component);
if(cs_error != kErrNone)
{
    /* Do something. */
}

Solution

  • From the point of conciseness, the first two if blocks are clearly better than the third one.

    In fact, there is no significant difference between the first if and the second if as you are simply changing the sides of the comparison expression.

    The third one unnecessarily adds one more statement as the assignment of a value to cs_error can be smartly combined into the if block. But yes, there is a chance of error if you are not careful about the braces.