in Programming in C
820 views
0 votes
0 votes
int foo( int a, int b)
{
    int c = a-b;
    c = c&(0x80000000);
    return (!c)*a +(!!c)*b;
}
in Programming in C
820 views

2 Answers

0 votes
0 votes
here & is bitwise and ,  and 0x8000000 is an hexadecimal number  c calculates a-b and the result is bitwise anded with the hexadecimal nuumber which comes 0 for small numbers e.g if a=14 b=6 then c=8 in bits 1000 & 100000000000=0 !c=1  and !!c=0 so above function will result the value of a .   it may also return b if hexadecimal number is small say 0x8 then anded result may be non  0  and its complement will be 0
0 votes
0 votes

The function returns the largest of the two numbers a and b.

In C, the most significant bit(MSB) is set to zero for positive numbers and to 1 for negative numbers. When the value of a-b is stored in the variable c, the MSB is set if b is larger and is not set if a is larger or is equal. The & operator is bitwise AND which is generally used to mask a few bits. Here, the hexadecimal number 0x80000000 is used to mask all bits except the MSB. Hence, c is set to zero if  a is larger and is set to a negative value if b is larger. The ! operator is the negation operator. It sets a non-zero value to zero and zero value to one. Hence, only one of (!c) and (!!c) values will be one and the other will be zero. The return statement returns the largest of a and b.

Related questions