开发者

how to change the switch-case statement to if-else statement

int number;
cin>&g开发者_Go百科t;number;

switch (number)
{
    case 1:
            cout<<"My Favourite Subject is";
            break;
    case 2:
            cout<<"Fundamentals of Programming";
            break;
    case 3:
            cout<<"Exit";
            break;
    default:
            cout<<"Invalid Data";
}


You replace switch statement with if-else

if (number == 1)
{
}
else if (number == 2)
{
}
...
{
}
else
{
    // default here
}


//Hey this is fun!
int number;
cin>>number;

// ultra const!
static const char const * const table[] =
{
  "Invalid Data",
  "My Favourite Subject is",
  "Fundamentals of Programming",
  "Exit"
};

cout<<table[number&3];

//Who needs if statements!!?


Check whether number is equal to the first value from switch, if equal then output text, otherwise(else) check next number.

if ( number == /*put here value to check*/ )
  // print some text
else
  // do something else


This is my favorite, even though it is not what you asked for:

string res =
  number==1 ? "My Favourite Subject is" :
  number==2 ? "Fundamentals of Programming" :
  number==3 ? "Exit" :
  number==4 ? "Invalid Data" :
  "";

cout<<res;

The good side here is that you don't have to constrain yourself to integer comparison. Instead of number==1 you can use any kind of complexComparisonReturningBoolean(number).


Also just for fun: Just use capital letters and semi-colon instead of colon. Ah, and don't forget to add an evil macro :)

#define SWITCH(s) for(int switch_=s, b=1;b;b=0) {
#define CASE(n) } if ( switch_ == n ) {
#define DEFAULT }

int number;
cin>>number;

SWITCH(number)
{
    CASE(1);
        cout << "My Favourite Subject is";
        break;
    CASE(2);
        cout << "Fundamentals of Programming";
        break;
    CASE(3);
        cout << "Exit";
        break;
    DEFAULT;
        cout << "Invalid Data";
}

This kill the 'switch' and if 'for' loop are not allowed, it is also possible to use a BREAK macro, but it is even more evil.


Replace the case statement with an if statement:

if (number == 1) {
    cout<<"My Favourite Subject is";
} else if (number == 2) {
    cout<<"Fundamentals of Programming";
} else if (number == 3) {
    cout<<"Exit";
} else {
    cout<<"Invalid Data";
} 


if (number == 1) {
cout << "blah1";
}
else if (number == 2) {
cout << "blah2";
}
else if (number == 3) {
cout << "blah3";
}
else { cout << "default";
}


Try :
if (number < 1 || number > 3) {
//
} else if (number == 1) {
//
} else if (number/2 == 1) {
//
} else if ((number - 1)/ 2 == 1) {
//
}
This helps you get more math expertise than just checking for equality.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜