# Thread: Comparing integers the short way

1. ## Comparing integers the short way

I saw this in a project (simplified of course). Is that a good way to do it or should I use an if statement instead?

Code:
```#include <stdio.h>
#include <stdlib.h>

int main()
{
int a = 10;
int b = 20;

int rv = a == b;
printf("rv=%d\n", rv);

return 0;
}``` 2. If you really just need to store 0 into a variable if the integers are not equal and 1 if they are equal, go ahead: it is guaranteed to work that way. 3. Originally Posted by laserlight If you really just need to store 0 into a variable if the integers are not equal and 1 if they are equal, go ahead: it is guaranteed to work that way. 4. Think how you would use this in a real program. What would you do if a == b, or if a != b. In a real program, would this method be more efficient than a simple if( a == b)...? 5. I prefer a simple if(a== b). It's just that I found this in one of our project and got a bit puzzled. 6. Originally Posted by hzcodec I prefer a simple if(a== b). It's just that I found this in one of our project and got a bit puzzled.
I'd be puzzled too! I would love to see this person's code for this and other surprises! ;^) 7. Originally Posted by hzcodec I prefer a simple if(a== b). It's just that I found this in one of our project and got a bit puzzled.
It's not really a matter of preference but a matter of what you are actually trying to accomplish in a real program. If all you want to do is assign 0 or 1 to a variable based on the comparison then
Code:
`x = a == b`
is perfectly acceptable, and generally more efficient than
Code:
```if (a == b)
x = 1;
else
x = 0;```
(ignoring compiler optimizations that would turn the latter into the former).

In my opinion, the former code is better, the latter code is amateurish.

Of course, if you want to do something more than simply set a variable to the result, then you would need the if statement. 8. Originally Posted by algorism ... Of course, if you want to do something more than simply set a variable to the result, then you would need the if statement.
Or the ?: operator  9. Originally Posted by TechnoGourmet Or the ?: operator Which is really just syntactic sugar for an if statement, i.e., it still involves a jump in the code (with the resultant potential cache miss penalty). Popular pages Recent additions #include, int, printfrv=%dn, rv;, statement 