Do compiler generates a if-elseif-elseif-else.. statements for normal switch cases(I mean, case labels are NOT in a narrow range) or do it generates the Jump statement for switch cases???
Printable View
Do compiler generates a if-elseif-elseif-else.. statements for normal switch cases(I mean, case labels are NOT in a narrow range) or do it generates the Jump statement for switch cases???
I suppose it depends on many things.
You would need to study the generated code from many compilers to get some kind of "consensus" view as to how they deal with a specific code example.
I have seen if-the-else equivalents running through the cases if there are few. I have also seen indexing into an array of destination instruction addresses when the compiler detected a contiguous set of integer cases. Thirdly I have seen a compiler generate binary search code if the number of choices is huge and the case numbers are all over the place. It generated a sorted address table.
They do all sorts of things including some things you've thought of and some things you haven't.
They'll use whatever seems the best at the time, for the options they have available.
Yes, or something else entirely.
For an overview of how compilers deal with this, see the article on page 103 of http://www.gccsummit.org/2008/gcc-2008-proceedings.pdf. GCC implements something like http://ivoras.net/papers/switch-complexity.pdf.