Piece
switch [C# C++ Java] fall through
More Code
2018. 6. 24. 20:08
참고 :
switch 구문에서 fall-through 지원 여부를 C# C++ Java 각각에 대해 알아보자.
C# C++ Java 공통 코드는 아래와 같다.
int number = 2;
switch (number)
{
case 1:
// print "one" statement for C# C++ Java respectively
break;
case 2:
// print "two" statement for C# C++ Java respectively
break;
case 3:
// print "three" statement for C# C++ Java respectively
break;
default:
// print "hello" statement for C# C++ Java respectively
break;
}
/* Output
two
*/
위 코드에서 case 구문만 있고, print 구문과 break 구문이 모두 없는 경우를 살펴보자.
// [C#] switch : fall-through
using System;
namespace Sharp1
{
class Program
{
static void Main(string[] args)
{
int number = 2;
switch (number)
{
case 1: // OK
case 2: // OK
case 3:
Console.WriteLine("three");
break;
default:
Console.WriteLine("hello");
break;
}
}
}
}
/* Output
three
*/
// [C++] switch : fall-through
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
int number = 2;
switch (number)
{
case 1: // OK
case 2: // OK
case 3:
cout << "three" << endl;
break;
default:
cout << "hello" << endl;
break;
}
return EXIT_SUCCESS;
}
/* Output
three
*/
// [Java] switch : fall-through
package package1;
public class Program {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1: // OK
case 2: // OK
case 3:
System.out.println("three");
break;
default:
System.out.println("hello");
break;
}
}
}
/* Output
three
*/
print 구문은 있고, break 구문만 없는 경우를 살펴보자.
C++과 Java는 이런 경우 fall-through를 허용하고, C#은 허용하지 않는다.
// [C#] switch : fall-through
using System;
namespace Sharp1
{
class Program
{
static void Main(string[] args)
{
int number = 2;
switch (number)
{
case 1: // Error
Console.WriteLine("one");
case 2: // Error
Console.WriteLine("two");
case 3: // Error
Console.WriteLine("three");
default:
Console.WriteLine("hello");
break;
}
}
}
}
// [C++] switch : fall-through
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
int number = 2;
switch (number)
{
case 1: // OK
cout << "one" << endl;
case 2: // OK
cout << "two" << endl;
case 3: // OK
cout << "three" << endl;
default:
cout << "hello" << endl;
break;
}
return EXIT_SUCCESS;
}
/* Output
two
three
hello
*/
// [Java] switch : fall-through
package package1;
public class Program {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1: // OK
System.out.println("one");
case 2: // OK
System.out.println("two");
case 3: // OK
System.out.println("three");
default:
System.out.println("hello");
break;
}
}
}
/* Output
two
three
hello
*/