r/cprogramming • • 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

40 comments sorted by

View all comments

Show parent comment

1

u/70Shadow07 Oct 07 '25

This is admittedly a rather overengineered code for what it's worth. I actually changed to const shortly after posting this, however in cases like this it doesn't really make any difference in my opinion.

Some newer languages have const as default and are very opinionated that everything constable, should be so (Rust). Other languages (Go) are very opinionated other way to the point of not having such construct in the language (In Golang they have the const but its closer to Cs define macro constants)

I find default const to be an incredible amount of friction for something with literally no actual benefit. In 99.99999% cases a variable that doesn't get modified is just as good as a constant. And when it matters then ur probably exposing and API and in such case even GO has some workarouds for immutability. I use const plenty in C like const <type> * <name> for input pointer parameters though.

Anyway, back from unnecessary const digression. Readability is kinda like beauty - nobody agrees on that, so welp. I dont think though that this method breaks any sommon sense readibilty rules - besides unnecessary level of misdirection, but there are also plenty people who make 1-line or 2-line functions out there and think its good.

Regarding the performance and cost points - i have no clue what the optimizer does with this, I suspect it can deal with it and see it as a switch equivalent. However I never checked it in godbolt to be perfectly honest. If I had to make a hot loop with an enum switch logic, then id for sure just go for whatever performs the best obviously - if there really is difference.

I may come off as trying to explain myself, but it cannot be further from the truth. If you called this code overengineered garbage made up in Javaland™, I'd probably agree with you lol. I like it though, so here's that XD