java - Switch 语句 : Is the logic different in C v/s. Java 等其他语言?

标签 java c++ c if-statement switch-statement

我正在浏览 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 - Switch 语句 : Is the logic different in C v/s. Java 等其他语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512816/

相关文章:

java - javaFx 中的内存使用情况

c++ - 在扣除 auto 之前使用 boost::hana::eval_if_t

c++ - 为什么 gcc 和 clang 都不发出任何警告?

c - ffmpeg 程序员使用的 lib Swscale 是做什么用的?

java - 如何在recyclerview中获取getFirstVisiblePosition()和getChildAt(0)

java - 如果重新排列两个字符串,如何比较它们

c++ - 在 C++ 中使用 RegisterWaitForSingleObject 将参数传递给回调函数

c++ - 如何取消初始化 std::experimental::Optional

c - 如何通过配置文件控制c程序的执行流程。该文件使用重定向运算符 (<) 传递

java - 从项目目录而不是原始目录应用的相对文件路径