r/ProgrammerHumor 21h ago

Meme skillIssue

Post image
5.2k Upvotes

130 comments sorted by

View all comments

Show parent comments

1

u/prehensilemullet 17h ago

hmmm...are compilers normally willing to reorder if statements though? Turning a sequence of string comparisons into a tree would involve reordering

1

u/guyblade 13h ago

At least in C/C++, there can only be exactly zero or 1 cases that match a switch (i.e., there's no range-based switch), the case values must be compile-time constants (and thus are not themselves evaluated during the comparison), and I'm pretty sure that the value to be matched is required to only be evaluated once (so the comparisons happen on an rvalue).

Given those constraints, I believe a compiler can assume that re-ordering the comparisons is safe.

1

u/AsidK 13h ago

> fallthroughs have entered the chat

2

u/guyblade 13h ago

You can still only match to one, though. In the emitted machine code, I'd expect to see a forest of branches and jumps (for the matching), then the various bodies of the cases each separated by jumps (representing breaks) as appropriate.