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?
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);
}
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
}
If you want to keep it on 1 line:
if ((A = B), A == 1)
does the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With