Jump to content

A Question About Switch Statement

Recommended Posts

Cosider the next code:



switch (a)



case 1:

a = a + 1;


case 2:


a = a + 1;


case 3:





Typically a "break" statement is inserted for each case so that once the condition is satisfied the code does not check further cases.

Obviously if it is not inserted then all cases will be checked, however I could not find documentation for the following - If the tested variable changes value within one of the cases in the switch, will the new value be used on the next case satement or does it maintain the entry value.

Or in this example will "a" only increase to 2 or will it also do_something(), increase to 3 and do_another_thing()?



Link to post
Share on other sites

I know how this *should* work. The tested value is tested once only at entry to the switch statement. So in this case, the code in all three cases is executed in sequence and at the end "a" will be equal to 3 and both do_something() and do_another_thing() will be executed.

Link to post
Share on other sites



Thats natural.

Althought very often used as it, the "switch" construct is not a direct replacement for an "if .. else if ... else" construct.

The semanthics are quite different and the "switch" is much more useful when building sequences of code with multiple entry points.

There is a correct place for each one but sometimes both can fit.


Just my 2 cents ...


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...