Why the switch statement cannot be applied on strings?

前端 未结 20 2570
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
20条回答
  •  醉话见心
    2020-11-22 04:40

    That's because C++ turns switches into jump tables. It performs a trivial operation on the input data and jumps to the proper address without comparing. Since a string is not a number, but an array of numbers, C++ cannot create a jump table from it.

    movf    INDEX,W     ; move the index value into the W (working) register from memory
    addwf   PCL,F       ; add it to the program counter. each PIC instruction is one byte
                        ; so there is no need to perform any multiplication. 
                        ; Most architectures will transform the index in some way before 
                        ; adding it to the program counter
    
    table                   ; the branch table begins here with this label
        goto    index_zero  ; each of these goto instructions is an unconditional branch
        goto    index_one   ; of code
        goto    index_two
        goto    index_three
    
    index_zero
        ; code is added here to perform whatever action is required when INDEX = zero
        return
    
    index_one
    ...
    

    (code from wikipedia https://en.wikipedia.org/wiki/Branch_table)

提交回复
热议问题