Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put condition check and variable assignment in one if statement

Tags:

c

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?

like image 451
deddebme Avatar asked Jul 28 '11 14:07

deddebme


3 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);
}
like image 72
Ferdinand Beyer Avatar answered Oct 26 '22 03:10

Ferdinand Beyer


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
}
like image 21
Kerrek SB Avatar answered Oct 26 '22 04:10

Kerrek SB


If you want to keep it on 1 line:

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

does the same thing.

like image 22
noelicus Avatar answered Oct 26 '22 05:10

noelicus