Switch语句:C中的逻辑是否不同v/s。其他语言,例如 Java?

Switch Statement: Is the logic different in C v/s. other languages like Java?

我正在学习 this C 编程教程。它说:

The switch-statement is actually entirely different(from other languages) and is really a "jump table". Instead of random boolean expressions, you can only put expressions that result in integers, and these integers are used to calculate jumps from the top of the switch to the part that matches that value. Here's some code that we'll break down to understand this concept of "jump tables".

但是,需要比较switch语句的大小写,直到找到匹配项(否则返回默认值。)

那么它与多个 if-else 语句有何不同?或者,它只是一个语法糖?我是不是漏掉了什么重要的东西?

它的实现方式似乎取决于编译器。 How Switch case Statement Implemented or works internally?

但通常 switch 语句有一个允许编译器对其进行优化的前提条件,这与 just if 语句不同,后者是您要比较的项目始终是整数类型 (char/int/long ).

其他语言允许将可在编译时求值的原语用作 switch 语句变量(C# 中的字符串)。

但总的来说,除了潜在的加速(以及如果你不中断可能发生的失败),与一堆 ifs 没有行为差异。

Java 实现类似于 GCC 4.8。 javac 编译为:

  • tableswitch 如果 table 是紧凑的,即 O(1)
  • lookupswitch如果不是,这是一个O(log(n))二分查找

GCC 使用了类似的技术:

  • O(1) 跳转 table 如果与 *%rax
  • 紧凑
  • O(log(n)) else if 二分查找 otherwise

可以在以下位置找到 compact 的定义:

  • Java:
  • 海湾合作委员会:How Switch case Statement Implemented or works internally?

为了观察这一点,只需反编译最少的测试用例:

  • 在 Java 和 javap
  • C 语言 objdump -S

压缩示例:

switch (i) {
    case 0:
        j = 0;
    break;
    case 1:
        j = 1;
    break;
    case 2:
        j = 2;
    break;
    case 3:
        j = 3;
    break;
    case 4:
        j = 4;
    break;
    case 5:
        j = 5;
    break;
};

非紧凑示例:

switch (i) {
    case 0:
        j = 0;
    break;
    case 1:
        j = 1;
    break;
    case 0x10:
        j = 2;
    break;
    case 0x100:
        j = 3;
    break;
    case 0x1000:
        j = 4;
    break;
    case 0xFFFFFFF:
        j = 5;
    break;
};