4 ms·
He has a some good points, but the "switch" statement needs an integer for a reason... a switch can be converted a jump table in assembly language, so that the
by antiquark 11y ago
He has a some good points, but the "switch" statement needs an integer for a reason... a switch can be converted a jump table in assembly language, so that the "case" can be arithmetically determined and instantly jumped to. The reason being: MOAR SPEED! A jump table is a lot faster than a sequence of else-if statments.
- shiro 11y agoThe compiler knows the type of the value it switched upon and generates code accordingly (efficient code on int values, dumb if-chain on other values), doesn't it? Sure it may become hard to tell if the code is efficient or not, but that property has already long been lost with operator overloading.
- sago 11y agoI don't see why that follows. If switch is given an integer, the compiler could create a jump table, otherwise it can use an if statement block (or some other kinds of implementation). There's nothing in C++ that says certain statements must always have the same compiled code.
- Grishnakh 11y agoSo why can't the compiler be smart enough to use a jump table when this is possible, and fall back to a sequence of else-if statements when it's not? The compiler should even be able to make a more optimal sequence of assembly tests and jumps than by writing this code manually.