开发者

Put a condition check and variable assignment in one 'if' statement

开发者 https://www.devze.com 2023-03-23 19:00 出处:网络
I am looking at some legacy C code and got confused. It is something like: UINT A, B = 1; if((A = B) == 1) {

I am looking at some legacy C code and got confused. It is something like:

UINT A, B = 1;
if((A = B) == 1) {
   retur开发者_开发问答n(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.


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);


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

This code sample is equivalent to just:

return (TRUE);
0

精彩评论

暂无评论...
验证码 换一张
取 消