switch在C++与C#中的一些差异

11 篇文章 0 订阅
参考链接
[url]http://blog.csdn.net/weiwenhp/article/details/7951743[/url]


平时碰到分支条件判断最常用的是if else语句,不过有时要是分支条件太多用switch就更直观,方便一点.先举两个简单的例子.

[color=red][b]C++:[/b][/color]

int num = 2;

switch(num)
{
case 1:cout<<"one";break;
case 2:cout<<"two";break;
case 3:cout<<"three";break; //break可省略
default:cout<<"default";break; //default 非必须,可以省略
}



[color=red][b]C#:[/b][/color]

int num = 2;
switch (num)
{
case 1: Console.WriteLine("one"); break;
case 2: Console.WriteLine("two"); break;
case 3: Console.WriteLine("three"); break; //break不能省略
default: Console.WriteLine("default"); break; //default 可省略.
}



C++,C#中swith的用法几乎是一模一样了.只有一些细小的差别,C#在C++的基础上做了一点改进.

[color=red][b]区别:[/b][/color]
1. C++中switch()括号中的变量类型只能是整形或者能默认转换成整形.比如[color=red]int,long,bool,char,enum[/color].(当然表达式也行,只要结果符合前面条件).但float,double,string就不行.另外自定义的类型,比如某个class,如果类中有运算符重载,class能默认转换成int.那也可以.不过一般情况很少会在switch中用到自定义的类型吧

C#中switch()括号中的变量类型可以是[color=red]byte,short,int,long,bool,enum[/color]另外还有string,这个在C++中是不行的.跟c++一样,可以用表达式,但float,double是不行的.自定义类型如可转换也行.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch04Ex03
{
class Program
{
static void Main(string[] args)
{
const string myName = "karli";
const string sexyName = "angelina";
const string sillyName = "ploppy";
string name;

Console.WriteLine("What is your name?");
name = Console.ReadLine();

switch (name.ToLower())
{
case myName:
Console.WriteLine("You have the same name as me!");
break;
case sexyName:
Console.WriteLine("My, what a sexy name you have!");
break;
case sillyName:
Console.WriteLine("That's a very silly name.");
break;
}

Console.WriteLine("Hello {0}!", name);
Console.ReadKey();
}
}
}


2. [color=red]C++中break是可以省略的[/color].但这样容易造成一个问题.如果没有break当某个分支符合条件执行完了后,会接着执行后面的分支.在上面的例子中,如果break全部去掉.结果会是twothreedefault

[color=red]而C#要你强制性使用break[/color],不用的话在编译时就会报错.这样就不会犯C++中因忘记写break而出现的错误.

补充:其实也可以用return替换break.只不过return是表示退出整个函数,而break只是退出switch这个语句块.

如果switch的语句块中的逻辑比较复杂还可以综合使用goto语句.

比如

int num = 2;
bool check = false;

switch (num)
{
case 1: Console.WriteLine("one"); break;
case 2: Console.WriteLine("two"); goto label;
case 3: Console.WriteLine("three"); break;
label: default: Console.WriteLine("default"); break;
}


当然很多很多人都说过在写代码时尽量另用goto语句,不得万不得已少用了.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值