![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Oct 2005
Posts: 52
Rep Power: 4
![]() |
switch statement
just a quick question about switch statements. is it true that you always have to use break; at the end of each case in a switch statement? Someone was trying to explain a way to me where you don't but every text book i've read says you must.
|
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Only if you don't want to execute the next case. That's most of the time.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#3 |
|
Professional Programmer
|
And a short example :
int n ;
switch(n){
case 0:
case 1:
case 2: System.out.println ( "the number is <= 2"); break;
case 3:
case 4:
case 5: System.out.println ( "the number is >=3 and <= 5"); break;
default : System.out.println ( "the number is grater than 5"); break;
}
__________________
Don't take life too seriously, it's not permanent ! |
|
|
|
|
|
#4 |
|
Expert Programmer
|
just to let you know xavier... that won't do anything since n is not defined :p
now if you did something like this int n = 0;
while(n < 3)
{
switch(n)
{
case 0: System.out.println("0"); break;
case 1: System.out.println("1"); break;
case 2: System.out.println("2"); break;
}
n++;
}it would work
__________________
|
|
|
|
|
|
#5 |
|
Professional Programmer
|
Yeah, you'r right, but the focus was the switch statement. I guess he cuold try the code a few times and initialize n to different values. I'm sure he would have realized that :p
__________________
Don't take life too seriously, it's not permanent ! |
|
|
|
|
|
#6 |
|
Newbie
Join Date: Sep 2006
Posts: 8
Rep Power: 0
![]() |
I thought you had to use break all the time as well. Im glad you asked that
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Help with a switch | Varrickmana | C++ | 11 | May 22nd, 2006 7:34 PM |
| Trouble with a swith statement | cjaime | C | 10 | Nov 8th, 2005 12:09 PM |
| New Switch, FTP Problems | ViOLATiON | Coder's Corner Lounge | 6 | Sep 13th, 2005 2:44 PM |
| Multiple IF statements, perhaps? | foxcity911 | PHP | 7 | Jun 22nd, 2005 4:33 PM |
| Switch statement | Hellion | C++ | 5 | Apr 11th, 2005 8:51 AM |