为什么在c / c ++中,开关的优化方式与链接方式不同?

Square的以下实现产生了一系列cmp / je语句,就像我期望的链式if语句一样:

int square(int num) {
    if (num == 0){
        return 0;
    } else if (num == 1){
        return 1;
    } else if (num == 2){
        return 4;
    } else if (num == 3){
        return 9;
    } else if (num == 4){
        return 16;
    } else if (num == 5){
        return 25;
    } else if (num == 6){
        return 36;
    } else if (num == 7){
        return 49;
    } else {
        return num * num;
    }
}

并生成以下数据表以供返回:

int square_2(int num) {
    switch (num){
        case 0: return 0;
        case 1: return 1;
        case 2: return 4;
        case 3: return 9;
        case 4: return 16;
        case 5: return 25;
        case 6: return 36;
        case 7: return 49;
        default: return num * num;
    }
}

为什么gcc无法将最上层的优化为最下层的?

Dissassembly for reference: https://godbolt.org/z/UP_igi

评论