Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# have break if it's not optional? [duplicate]

When I create a switch statement in VS2008 C# like this (contrived):

switch (state) {     case '1':         state = '2';     case '2':         state = '1'; } 

it complains that I'm not allowed to drop through:

Control cannot fall through from one case label ('case '1' (0x31):') to another

If you're not allowed to drop through, then what is the purpose of the break statement at all? Why didn't the language designers just leave it out and automatically jump to the end of the switch statement instead of forcing us to put in an unnecessary construct?

like image 804
paxdiablo Avatar asked Jun 24 '10 09:06

paxdiablo


People also ask

Why is %d used in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Why do we write in C?

It was mainly developed as a system programming language to write an operating system. The main features of the C language include low-level memory access, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like an operating system or compiler development.

Why semicolon is used in C?

Role of Semicolon in C: Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


1 Answers

Basically to make it more familiar to C/C++/Java developers. Personally I think it was a mistake, but that's the reasoning.

I would have preferred a forced block:

case '1': { } 

Aside from anything else, that would have avoided the weird variable scoping situations for switch/case. You could still have multiple case labels, of course:

case '0': case '1': { } 

It might also be nice to be able to list multiple cases more simply:

case '0', '1': { } 

Oh, and a slight nit-pick about your description of the existing language: you don't have to have a break. It's just that the end of the case has to be unreachable. You can also have throw, goto or return. There may be others that I've missed, too :)

like image 51
Jon Skeet Avatar answered Oct 11 '22 20:10

Jon Skeet