避免分支

//This one actually compiles to assembly that doesn't have any conditionals:

#include <stdio.h>
#include <stdlib.h>

void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}


//Edit: Added '&' so it will consider the address hence evading the pointer errors.
//This version of the above in standard C, since it doesn't rely on arithmetic on function pointers:

#include <stdio.h>
#include <stdlib.h>

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}


#include <stdio.h>
int i = 0;
p()    { printf("%d\n", ++i); }
a()    { p();p();p();p();p(); }
b()    { a();a();a();a();a(); }
c()    { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }

//I'm surprised nobody seems to have posted this -- I thought it was the most obvious way. 1000 = 5*5*5*8.
//People have posted this. The other versions pass the number to print instead of using a global, but it's essentially the same solution.
posted @ 2020-11-16 09:11  fndefbwefsowpvqfx  阅读(56)  评论(0编辑  收藏  举报