Put Condition Check and Variable Assignment in One If Statement

Put Condition Check and Variable Assignment in One If Statement

I am looking at some legacy C code and got confused, it is something like:

UINT A, B = 1;
if((A = B) == 1){
   return(TRUE);
} else {
   return(FALSE);
}

We all know there will be a compiler warning if we do if(A = B), but here it looks like the 'if' is checking A against 1, am I correct?

5 Answers

First, it assigns the value of B to A (A = B), then it checks if the result of this assignment, which is A and evaluates to 1, is equal to 1.

So technically you are correct: On the way it checks A against 1.

To make things easier to read, the code is equivalent to:

UINT A, B = 1;
A = B;
if(A == 1){
   return(TRUE);
} else {
   return(FALSE);
}
3

Rather, your code is always assigning B to A, and it is moreover checking whether the value of B (and thus also A) is equal to 1.

There's nothing "legacy" about this, this is generally a pretty handy idiom if you need the result of an operation but also want to check for errors:

int result;
if ((result = foo()) != -1)
{
  printf("The result is: %i\n", result);
}
else
{
   // panic
}
1

If you want to keep it on 1 line:

if ((A = B), A == 1)

does the same thing.

We are trying to avoid if statements to make code more readable.

UINT A, B = 1;
bool fResult = false;

fResult = (A == B);

return(fResult);

And if there must be an condition to act on (not) equality, see this example.

UINT A, B = 1;
bool fResult = false;

fResult = (A == B);

if(fResult)
{
  doThis();
}
else
{
  doThat();
}

return(fResult);
1

Correct. The value A has after the assignment will be compared to 1.

This code sample is equivalent to just:

return (TRUE);
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.