Re: New switch/case idea

new topic     » goto parent     » topic index » view thread      » older message » newer message
irv said...

I am failing to detect the logic in this discussion.

switch x -- x = 1, let's say 
   case 1 : print "one" 
   case 2 : print "two" 

Why on earth would anyone EVER expect this to print "onetwo", when x = 1?

Can anyone show me a justification for this? Or any example where some other construct wouldn't do the same thing in a clearer way? Or have I simply misread some posts and don't understand?

Irv, that is the way switch is designed, for many valid reasons. We use switch galore w/your exact situation in Euphoria's internal code (both C and Euphoria).

The problem most new people have with switch is they think of it as if/elsif/elsif/else. It is not. It's more like a goto. Once a case matches, execution of the switch block continues w/o regard for any other case statement. Case statements are just labels, basically, that is used for jumping into the switch at a given location.

A switch with fallthru is not a if/elsif/else statement. Here is a valid example:

switch op with fallthru do 
	case RETURNT then 
		opRETURNT() 
		break 
	case RHS_SLICE then 
		opRHS_SLICE() 
		break 
	case RHS_SUBS then 
	case RHS_SUBS_CHECK then 
	case RHS_SUBS_I then 
		opRHS_SUBS() 
		break 
	case RIGHT_BRACE_2 then 
		opRIGHT_BRACE_2() 
		break 
	case RIGHT_BRACE_N then 
		opRIGHT_BRACE_N() 
		break 
end switch 

See for many, like RHS_SLICE, only one condition should enter the switch. However, for RHS_SUBS_*, all three of them enter and perform the same action. This is very valuable and in more complex situations (which I didn't choose here for space reasons), it saves a ton of time and makes things much clearer once you understand what a switch does. Please see the euphoria source code (both C and Euphoria code) for some pretty complex and valuable examples.

Jeremy

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu