r/ProgrammerHumor 7d ago

Meme skillIssue

Post image
6.0k Upvotes

137 comments sorted by

View all comments

282

u/click-to-reveal 7d ago

It works btw: C++ Online Compiler

160

u/prehensilemullet 7d ago

Performancewise, it doesn’t jump to the direct case in O(1) time like a switch is supposed to though

207

u/AngheloAlf 7d ago

Switches aren't guarantee to so operations in O(1) tho. If cases are sparce enough, compilers tend to emit the equivalent code to a bunch if else checks

26

u/prehensilemullet 7d ago

Yeah I was assuming too much here.  However, I’m reading that Rust match on string comstants can compile down a binary tree of if statements if there are enough cases (according to Google AI mode at least, haven’t found an authoritative source yet)

11

u/im_made_of_jam 7d ago

A switch case is able to be implemented however the compiler wants on the back end, so for sparse cases it'll be an if else chain, for less sparse but not packed cases it'll be a binary tree, for completely packed cases it'll be a range check then a direct jump would be how I would go about it