
Computing for the minimum/maximum values between two integers is a fairly common task in many computer programming problems. This can easily be done with branching (i.e. the use of the if-else conditional statements).
Here’s a trick in C programming that computes the minimum/maximum between two integers WITHOUT BRANCHING (and using math.h’s built-in min/max function). Note that this makes use of the AND (&) bitwise operator and XOR (^) bitwise operator.
//start
int a = 300;
int b = 200;
int min;
int max;
min = b ^ ((a ^ b) & -(a < b)); //gives min value
max = a ^ ((a ^ b) & -(a < b)); //gives max value
printf(”%d\n”, min);
printf(”%d\n”, max);
//end

One of the very first programming exercise a beginner programmer would encounter is swapping the values of two variables. The solution is pretty much trivial:
//start
int a = 1;
int b = 2;
int temp;
printf(”Values before swapping a = %d b = %d\n”, a,b);
temp = a;
a = b;
b = temp;
printf(”Values after swapping a = %d b = %d”, a,b);
//end
Here’s a trick to
//start
int a = 1;
int b = 2;
printf(”Values before swapping a = %d b = %d\n”, a,b);
a = a ^ b;
b = b ^ a;
a = a ^ b;
printf(”Values after swapping a = %d b = %d”, a,b);
//end
TEACHING minds.
TOUCHING hearts.
TRANSFORMING lives.
The Peer Tutors Society greets De La Salle University a happy centennial! Join the festivities on June 16, 2011! Keep the Animo burning!

Be part of Lasallian History as DLSU opens its doors to the faithful to pray and to venerate the relic of St. La Salle, the patron saint of the teachers of the youth.

Know how it feels to get a 4.0?
Help someone else feel that way.
Become a Peer Tutor!
Just follow the instructions listed above.
For inquiries and/or updates, feel free to email us at dlsu.pts@gmail.com.

Having troubles with COMPRO[1or2] or INTRPRG?
Too shy to ask your professors?
Apply for a Peer Tutor now! Peer-to-Peer Tutoring is a FREE service.
PTS bulletin board is located at 2nd floor, Gokongwei Bldg (near the Warpzone).
For immediate questions and/or concerns, feel free to email us at dlsu.pts@gmail. com