Jump Table Switch Case question

前端 未结 6 604
孤街浪徒
孤街浪徒 2020-12-08 00:55

I am trying to understand some things about jump tables and its relationship between a switch case statement.

I was told that a jump table is a O(1) structure that t

6条回答
  •  借酒劲吻你
    2020-12-08 01:55

    Suppose you had an array of procedures:

    void fa() { 
     printf("a\n");
    }
    
    ...
    
    void fz() { 
     printf("it's z!\n");
    }
    
    
    
    typedef void (*F)();
    F table[26]={fa,fb,...,fz};
    

    Suppose you accept a character (from a-z) of input from the user and run fc:

    char c;
    switch(c) {
       case 'a': fa();break;
       case 'b': fb();break;
       ...
       case 'z': fz();break;       
       default: exit(-1);
    }
    

    Ideally this would be replaced with something like:

    if (c<'a' || c>'z') exit(-1);
    else (*table[c-'a'])();
    

    Naturally, you might make the table bigger so the range check wouldn't be necessary.

    The compiler would do this for arbitrary code, not necessarily function calls only, and would do it by storing the address to jump to (essentially, a goto). C doesn't directly support any sort of computed goto (indexing into a table or otherwise), but the CPU instructions for it are pretty simple.

提交回复
热议问题