4 ms·
I can't think of any case where `switch(true)` is what you actually want to do, barring some weird compiler workaround or hack or something. And the first one
by meowface 9y ago
I can't think of any case where `switch(true)` is what you actually want to do, barring some weird compiler workaround or hack or something.
And the first one is akin to:
if (data == 1) {}
if (data == 2) {}
if (data == 3) {}
...
if (data == thevalueIactuallywant) { doSomething(); }
- plorkyeran 9y ago`switch (true)` is insane, but it does actually work as the author intended it to in PHP. It just evaluates each of the case statements in order until one evaluates to true, so it's equivalent to an if/else chain.
- tonmoy 9y agoActually in the hardware world I see switch(true) a lot. It is very useful for creating a priority encoder. For example you have 3 interrupts with priorities int0 > int1 > int2. Then this code is pretty clean and concise: Switch(true) { Case(int0): // Do stuff for interrupt 0 Case(int1): // Do stuff for interrupt 1 ...
- meowface 9y agoI stand corrected. Assuming no fallthrough, what are the advantages of this over chaining if and else-if? Just to look cleaner?
- consz 9y agoI believe the point is to explicitly take advantage of the fallthrough.
- meowface 9y agoWell, then it would just be chaining if statements.
- tonmoy 9y agoNot much, but I’d say it is more maintainable as well (you can change priority/get rid of the top one without affecting the following lines)