Reputation: 495
I was wondering how the C compiler would handle the comparison operator '=='
I wish to create a function (in C) that compares two things without using the ==. I think it can be done some how by using bitwise operators ( &, |, ^, >>) however I can't seem to think of how to do it.
Anyone have ideas?
Thanks!
Upvotes: 0
Views: 518
Reputation: 5456
Other answers are good, but if you want only bitwise operators, do something like:
int is_equal(int a,int b) {
int bit=1;
while(bit) {
if ((a&bit)^(b&bit)) return 0;
bit<<=1;
}
return 1;
}
Upvotes: 0
Reputation: 44316
Since you're wondering how the compiler does it, it translates ==
into machine code that contains a cmp
instruction. This instruction compares two operands, and stores the result of the comparison. The result can be checked to see if the operands were equal, not equal, less than, greater than, etc.
In the case of using ==
in an if
statement, it would probably generate something like this:
cmp op1, op2
jne else_address
which basically means 'Compare the two values. If they are not equal, skip to the else block.'
Upvotes: 0
Reputation: 1513
What if you invert every bit of one of the values and then "&" the two values together. If the result is zero, then they should be equal.
int x=5;
int y=5;
int z=(~x)&y;
if(!(y>0||y<0)){
//Values are equal.
}
Why don't you want to use the "==" operator?
Upvotes: 0
Reputation: 121961
Without using ==
:
int is_a_equal_to_b(int a, int b)
{
if (a > b || a < b) return 0; /* Not equal. */
return 1; /* Equal. */
}
Upvotes: 1
Reputation: 18350
For integral types, if (!(a - b))
will work.
You might run into some funny problems with other types.
Maybe if (!(a ^ b))
?
Upvotes: 1
Reputation: 141829
Here's a simple way to check if two ints are equal without using ==
:
int x = 3;
int y = 3;
if(x < y || y < x)
printf("Not equal");
else
printf("Equal");
Upvotes: 6