Switch 语句的工作原理 [英] How Switch Statement Works

查看:43
本文介绍了Switch 语句的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

switch 语句如何立即下降到内存中的正确位置?对于嵌套的 if 语句,它必须对每个语句进行比较,但是对于 switch 语句,它会直接转到正确的情况.这是如何实施的?

How does a switch statement immediately drop to the correct location in memory? With nested if-statements, it has to perform comparisons with each one, but with a switch statement it goes directly to the correct case. How is this implemented?

推荐答案

有许多不同的方法可以将 switch 语句编译成机器码.以下是一些:

There are many different ways to compile a switch statement into machine code. Here are a few:

  • 编译器可以产生一系列测试,这并不是低效的,因为只有大约 log2(N) 个测试就足以在其中分配一个值N 种可能的情况.

  • The compiler can produce a series of tests, which is not so inefficient as only about log2(N) tests are enough to dispatch a value among N possible cases.

编译器可以生成一个值表和跳转地址,这些表依次被通用查找代码(线性或二分法,类似于bsearch())使用,最后跳转到对应的位置.

The compiler can produce a table of values and jump addresses, which in turn will be used by generic lookup code (linear or dichotomic, similar to bsearch()) and finally jump to the corresponding location.

如果 case 值足够密集,编译器可以生成一个跳转地址和代码表,检查 switch 值是否在包含所有 case 值的范围内,并直接跳转到相应的地址.这可能是与您的描述最接近的实现:但是使用 switch 语句,它会直接转到正确的大小写.

If the case values are dense enough, the compiler can generate a table of jump addresses and code that checks if the switch value is within a range encompassing all case values and jump directly to the corresponding address. This is probably the implementation closest to your description: but with a switch statement it goes directly to the correct case.

根据目标 CPU 的特定能力、编译器设置以及 case 值的数量和分布,编译器可能会使用上述方法中的一种或另一种,或它们的组合,甚至一些其他方法.

Depending on the specific abilities of the target CPU, compiler settings, and the number and distribution of case values, the compiler might use one of the above approaches or another, or a combination of them, or even some other methods.

编译器设计者花费大量精力尝试改进这些选择的启发式方法.查看程序集输出或使用在线工具(例如 Godbolt 的编译器资源管理器)查看各种代码生成可能性.

Compiler designers spend a great deal of effort trying to improve heuristics for these choices. Look at the assembly output or use an online tool such as Godbolt's Compiler Explorer to see various code generation possibilities.

这篇关于Switch 语句的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆