How do I transform an IF statement with 2 variables onto a switch function using C?

前端 未结 7 1907
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 07:49

I have an IF-statement that I want to transform into a Switch-statement... But it has 2 variables! Is it possible to do it on C?

It is a rock, paper, scissors game:

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 08:13

    You can nest your switch statements for each expression, such as

    switch(a)
    {
      case 'A':
        switch(b)
        {
          case 0: // do something with A0
            break;
          case 1: // do something with A1
            break;
          ...
        }
        break;
    
      case 'B':
        switch(b)
        {
          case 0: // do something with B0
            break;
          ...
        }
        break;
      ...
    }
    

    As you can see, this has the potential to get very ugly very quickly. If you have to branch based on combinations of values, then you're probably better off keeping the current structure.

提交回复
热议问题