Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Asking about function of default in switch

 
kumar abhay
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sir ,
Hope u r doin? fine . I m here with a problem n very much hoped that u will solve my problem .here is the 1st programe in java regarding Switch is given below:

my question is that:
In the first programe,the default was given in the beginning and in the 2nd programe default was given in the last.so how the compiler comes to know the position of the default in the programe .how the compiler works internally to recognise default.i hope that u will make me underestand .i will wait for your reply.
Take care
Kumar Abhay

[This message has been edited by Cindy Glass (edited October 02, 2001).]
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler processes the case staatements until it finds one that matches, finds the default, if not matches, or if there is no default statement, until the ending brace of the switch statement. I know the default is usually put at the end, but you atre correct, it can be put anywhere within the switch case labels, and the compiler will know to process it. AS for how the compiler does that internally, I don't know. I just know it works!

Bosun
 
shilpa kulkarni
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'default' mathces any value. so if you place the default case at the top, whatever the value of (b+1), the default will get executed.
for eg. if (b+1)=0, it will execute default, it will never go to case 0 (because of the break at the end of the case default).
whereas using the 2nd code, the default will be executed only if no other case mathces. so, if value of (b+1)=0, then case 0 will be executed.
i hope this helps to explain how the default is recognised/executed by the compiler.
 
Bill Krieger
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by shilpa kulkarni:
'default' mathces any value. so if you place the default case at the top, whatever the value of (b+1), the default will get executed.

The position of the default does not matter. In the following code:

The output is "Case one." The position of the "default" versus the "case" statement is completely irrelevent.
 
shilpa kulkarni
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops! I guess it does print "Case one".
Wonder where I got that from.....
Thanks for correcting me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic