Working of Switch Case

Today let us talk about the misconception of the working of the switch case statement.
I have heard from a lot of people that it just compares the cases and executes the block if it matches the case.

But the working in the background is quite different.
Let's go step by step:-

  1. Switch Case is not there to replace if else but to optimize it.
  2. If else goes sequence-wise from the top it checks conditions and goes through all conditions till the candidate condition is found.
  3. In switch case what happens is all the cases are treated as labels and each label is associated with a line number
  4. when a value is passed to the switch it straight away goes to the line number associated with that case label.
  5. this avoids the linear comparison of the if-else statement
  6. In a way switch case is a jump statement along with being a selection statement (just my opinion)
  7. This is why we have to use break after the every case block ends, the code knows the starting point of a block but not the end of it.

In the video on my linkedin post ,I have shown the execution flow of the switch case statement through the Trace function of Turbo C
[https://www.linkedin.com/posts/rahul-dubey-707b4452_basics-buildyourbase-learning-activity-6909762888496742400-dpYI]
(Since i was unable to upload a vidoe here)

Comments (0)