Checking state and assigning a variable in a single if statement

I look at some inherited C code and am confused, this is something like:

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

We all know that there will be a warning about the compiler if we do if (A = B), but here it looks like this: "if" checks A for 1, am I correct?

+7
source share
5 answers

First, it assigns the value B A ( A = B ), then checks whether the result of this assignment is equal to A and has a value of 1 equal to 1 .

So, technically you are right: along the way, it checks A for 1 .

To simplify reading, the code is equivalent to:

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

Rather, your code always assigns B A , and also checks to see if the value of B (and therefore A ) is 1 .

There is nothing "outdated" in this, it is usually a rather convenient idiom if you need the result of the operation, but you also need to check for errors:

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

If you want to save it in 1 line:

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

does the same thing.

+2
source

Correctly. The value of A after comparison will be compared with 1 .

This code example is simply equivalent:

 return (TRUE); 
0
source

We try to avoid operators to make the code more readable.

 UINT A, B = 1; bool fResult = false; fResult = (A == B); return(fResult); 

And if there should be a condition to act on (non) equality, see this example.

 UINT A, B = 1; bool fResult = false; fResult = (A == B); if(fResult) { doThis(); } else { doThat(); } return(fResult); 
0
source

All Articles