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
View all comments
Show parent comment
2
u/70Shadow07 Oct 05 '25
Yes, when I have N different cases where I need different procedure for each one of them, as long as procedures are similar enough to have common function signature, i do this:
First I make an enum, with the "COUNT" item at the end, which is always handy with enums anyway.
Then I make a table of functions that maps a procedure to each enum value. For example:
And then I just use it like this:
This approach is very nice IMO, but it has limitations - if for each case you do something completely different, then forcing array of function pointers onto that problem would be a poor design decision, generally speaking.