Sunday, July 12, 2009

Using inequality check in switch in c++?

I'm wondering if there's a way to do an equality check in each case with switch operator in c++.





Also, are switch operators generally faster a bunch of if-elseif statements?

Using inequality check in switch in c++?
switch and case statements can compile down to the same code as if then else if unless the conditionals are very complex.


switch only tests for equality against the constants in the case statement
Reply:Switch/case statements are just easier to read IMO. If you have more than 3 cases on a single variable, you should always use a switch/case





If you're comparing multiple variables in different cases under the same statement, if statements are better.





They pretty much compile down to the same assembly code, so they are all efficient.





The only way to speed up performance is if you are doing the same calculation or comparison in a loop, and comparing it everytime. Just put the result of the comparison or calculation in a local variable.





An example would be finding the length of a string each time in a loop when it doesn't change. Just extra work.


No comments:

Post a Comment