您的位置:首页 > 编程语言 > C语言/C++

C/C++/C# 中的switch case 比较

2011-05-13 16:01 369 查看
C

codeblocks+gcc



#include <stdio.h>
#include <stdlib.h>

int main()
{
    int nWeek = 1;
    switch (nWeek)
    {
        case 1:
            printf("周一 ");
        case 2:
            printf("周二 ");
        default:
            printf("其它 ");
            break;
            }
    return 0;
}




输出结果为:周一 周二 其它



当将nWeek = 2

输出结果为:周二 其他



理解:switch 通过nWeek的值找到入口标号,然后从这个标号开始顺序往下执行

可以通过在每一个case的结尾添加break语句来实现跳出,加有break语句的case类似else if 功能。



C++

与C相同



C#

每个case下面必须有break语句,除非该case下面为空语句,否则出错。

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

namespace ImplicitTypeVariable
{
    class Program
    {
        static void Main(string[] args)
        {
            int nWeek = 1;
            switch (nWeek)
            {
                case 1:
                    Console.Write("周一 ");
                    break;  //break 必不可少,除非case 下面是空的语句
                case 2:
                    Console.Write("周二 ");
                    break;
                default:
                    Console.Write("其它 ");
                    break;
            }

            Console.ReadKey();
        }

    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: