Make a program to print the smallest of two numbers using an if statement#

#include <stdio.h>
include <stdio.h>
int main() {
    int x = 9;
    int y = 5;
    int min;

    if (x < y) {
        min = x;
    } else {
        min = y;
    }

    printf("The smallest number is: %d\n", min);
    return 0;
}

Now how about Make a program to print the smallest of two numbers without using an if statement ???#

#include <stdio.h>

int main() {
    int x = 9;
    int y = 5;

    // Bitwise trick to find the minimum
    int min = y + ((x - y) & ((x - y) >> 31));

    printf("The smallest number is: %d\n", min);
    return 0;
}
  • x = 9, y = 5

  • x - y = 4 [9 - 5]

  • Binary of 4 (32-bit signed int)

  • 00000000 00000000 00000000 00000100

  • (x - y) » 31 → shifts it 31 bits to the right.

  • 4 » 31 becomes »> 00000000 00000000 00000000 00000000

  • which is 0

  • ((x - y) » 31)) »> Bitwise right shift — moves the bits 31 positions right

  • So (x - y) » 31 = became 0

  • (x - y) is positive, the result is 0

  • (x - y) is negative, the result is -1

  • (x - y) = 0 [4 positive]

  • y + ((x - y) & ((x - y) » 31)) became 5 + (4 & 0)

  • y = 5 which is the smallest number…..

Bitwise Trick — Fast in some cases — Hard to read and maintain#

If Statement —– Simple, readable May be slightly slower on old hardware due to branching#