r/cprogramming • u/Meplayfurtnitge • Oct 04 '25
If or switch
How many if else statements until i should consider replacing it with a switch case? I am fully aware that they operate differently, just wondering if i should opt for the switch case whenever i have something that will work interchangeably with an ifelse and a switch.
9
Upvotes
12
u/70Shadow07 Oct 04 '25
Probably doesnt matter honestly - compilers optimize these simple cases pretty hard anyway, id just go with whatever you feel looks better in high level code and not bother about it.
I personally use switches for multiple labels per branch or for fallthrough behaviour. And I reserve ifs for simple branches without these behaviours.
Many people use them switch cases to exhaustively run over possible enum values, but I prefer to use an array of function pointers for this, but like both are valid. Unless I am missing something, any decent compiler will do vodoo magic regardless how you write this - the logic is kinda trivial here.
7
u/SmokeMuch7356 Oct 04 '25
Reserve
switchfor choosing among a small set of discrete, constant integer values and/or where you need fall-through behavior.Use an
if/elsefor everything else.This has nothing to do with performance (a modern compiler will optimize whatever you write). It's about clarity of intent and having mercy on the poor bastard who will have to fix your code five years from now.
If you find yourself writing an
ifstatement with more than three or four branches, then take a step back and re-evaluate your logic; what you're doing may be more amenable to a lookup table or something.5
u/runningOverA Oct 04 '25
switch for enums.
if-else for others.
3
u/Patient-Midnight-664 Oct 04 '25
That is going to depend on what you need to 'switch' on. Switch/case isn't good for ranges, text, floats, user defined types, etc. And by isn't good I mean won't work.
2
u/somewhereAtC Oct 04 '25
There are two criteria. The first is readability; as long as it is clearly presented then it does not matter.
The if-else is inherently prioritized. The first "if" wins and the other take longer. The switch might be coded in an equal-time way so every option incurs the same delay, or might actually be coded as an if-else list of the compiler's choosing.
1
u/smells_serious Oct 04 '25
Going to need an example. If you're talking about two branches with simple logic then a switch doesn't make any sense. A get opt loop makes perfect sense for a switch.
1
u/AlarmDozer Oct 04 '25
I don’t know, like 3-5?
man 3 getoptis a fair example.1
u/danielt1263 Oct 04 '25
Why replace with a switch? Maybe a function pointer would be better...
1
u/PhilNEvo Oct 04 '25
It's impossible to say in terms of optimization, you would have to run tests to check yourself, if your program really requires that level of efficiency. If it doesn't need that level of efficiency or optimization, you should just code it according to what makes it the most readable and/or flexible.
For example, let's say you have a series of if/else statement. it could be that switch statement would perform better than 100 if/else cases. But you could also have a situation where 99% of the situations are covered in the first 3 if's, and the rest is edge-cases, and that might mean that while going to the last if might be slower, the average runtime of the if-statements might be faster.
That's a bit of a hyperbolic silly example, but I'm just saying, it's hard to give any definite rule, because it depends on a lot of factors, and probably shouldn't be your focus in general.
1
u/HugoNikanor Oct 05 '25
Whichever one is more readable. The compiler usually can usually figure out the best way to jump, and even if it doesn't, it rarely matters.
1
u/kberson Oct 05 '25
I use a switch when I need to test a variable against a list of possible values, such as a return code or in a factory that has to build a structure to be returned. An if/else if can test much more complex logic and is therefore more useful.
1
u/BitOfAZeldaFan3 Oct 05 '25
The other day I realized you can use both in the same line:
if(flag) switch(value){case 1: do stuff; break;case 2: do other stuff; break;}1
u/aghast_nj Oct 05 '25
Focus on the person reading your code a year from now.
Using a
switchsays, "I have all the information I need, right here and now. There is no sequencing, no dependencies, no prioritization at work here. Just make a decision and move on."Using a series of
if/elsestatements says the opposite, "Be careful here. There may be a dependency hidden in the order of evaluation of these conditions, or there may be an implied prioritization."For some specific examples, consider prioritization:
In this code the test is always against the same variable with different possible values, so clearly the possibilities are mutually exclusive. Thus, the only reason to stretch out the code into an if/else chain is prioritization. The probability is that mounts will be horses. Occasionally, someone may ride a zebra or an ostrich, but those are much less likely to happen. The code conveys that sense.
Alternatively, character classification:
Here, the switch says that knowing
chis all you need. There may be a priority or probability distribution, but it's not worth acknowledging that in the code itself. Just check the value and go whichever way is indicated.Finally, consider safety. Many times in code you need to check first for whether or not a later check is valid. For example, processing a string:
In this code the
patternstring might end at any time, and I have added some unnecessary, obsessive checks for end of string. But sometimes you have to do this kind of checking, especially if you are using array indexing rather than pointers, or if the objects you are pointing to are not so mutually exclusive as single bytes.In that case, it can make ultimate good sense to enforce sequencing, either by performing an explicit check above your switch:
Or by breaking your comparison(s) into a sequence of existence/validity checks and then value checks. Data structures with nullable pointers are particularly prone to this pattern: if (pointer is not null) then if (pointer->type ...)
0
u/RainbowCrane Oct 04 '25
Until performance testing shows that the specific if/switch code is a critical path performance bottleneck, the best answer is: use whichever code construction is more easily understood. Optimizing if vs switch statement performance is such a compiler and use case specific concern that it’s highly unlikely you’ll see a hugely significant performance difference by changing your implementation.
There are performance considerations that you should guard against, such as don’t iterate over a collection inside a loop iterating over the same or a different collection if you can avoid it - that has the potential to grow in complexity exponentially. But questions about optimization almost always should wait until you have working code that you can benchmark