How do I programmatically return the max of two integers without using any comparison operators and without using if, else, etc?

后端 未结 10 2180
一生所求
一生所求 2020-12-09 10:35

How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 11:07

    This is kind of cheating, using assembly language, but it's interesting nonetheless:

    
    // GCC inline assembly
    int max(int a, int b)
    {
      __asm__("movl %0, %%eax\n\t"   // %eax = a
              "cmpl %%eax, %1\n\t"   // compare a to b
              "cmovg %1, %%eax"      // %eax = b if b>a
             :: "r"(a), "r"(b));
    }
    

    If you want to be strict about the rules and say that the cmpl instruction is illegal for this, then the following (less efficient) sequence will work:

    
    int max(int a, int b)
    {
      __asm__("movl %0, %%eax\n\t"
          "subl %1, %%eax\n\t"
              "cmovge %0, %%eax\n\t"
              "cmovl %1, %%eax"
             :: "r"(a), "r"(b)
             :"%eax");
    }
    

提交回复
热议问题