什么是逗号操作符在switch语句是什么意思? [英] What does comma operator mean in a switch statement?

查看:328
本文介绍了什么是逗号操作符在switch语句是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个问题,并要求给输出。

  INT主要(无效){
    INT X = 2;
    开关(X){
        案例1,2,1:输出(案例1被执行);
            打破;
        案例2,3,1:输出(第2种情况实行);
            打破;
        默认:输出(我们执行默认情况下);
    }
    返回0;
}

以上code给出作为输出在Turbo C案例1执行,但在$ C $个cblocks和在线编译,它提供了编译错误。

哪一个是正确的?它是一个编译器错误或不?如果不是,为什么只在Turbo C的在code运行?


解决方案

  

它是一个编译器错误或没有。


在code是两种语言无效:情况前pression必须是一个常量前pression,和恒定的前pression不能包含逗号操作符。 (在C,这是明确指出,在C ++中,你必须拆开语法找到一个的恒前pression 的必须是一个的条件-EX pression 的,不能包含逗号)。

即使你被允许在这里使用逗号运算符中,开关语句仍然是无效的,因为2案件将都具有相同的价值,1。


  

如果不是为什么用code运行只在Turbo C的。


由于两种语言都自认为prehistoric编译器上次更新显著改变。如果你想从本世纪学习C或C ++的变种不使用它。

I was given a question and was asked to give the output.

int main(void){  
    int x = 2;  
    switch(x){  
        case 1,2,1: printf("Case 1 is executed");  
            break;  
        case 2,3,1: printf("Case 2 is executed");  
            break;  
        default : printf("Default case us executed");  
    }  
    return 0;  
}

The above code gives output as "Case 1 is executed" in Turbo C, But on codeblocks and compile online, it gives a compiler error.

Which one is correct? Is it a compiler error or not? And if not, why does the code run only on Turbo C?

解决方案

is it a compiler error or not.

The code is invalid in both languages: the case expression must be a constant expression, and a constant expression can't contain a comma operator. (In C, this is stated explicitly; in C++, you have to unpick the grammar to find that a constant-expression must be a conditional-expression, which can't contain a comma).

Even if you were allowed to use the comma operator here, the switch statement would still be invalid since two cases would both have the same value, 1.

And if not why does the code run only on turbo C.

Because both languages have changed significantly since that prehistoric compiler was last updated. Don't use it if you want to learn variants of C or C++ from this century.

这篇关于什么是逗号操作符在switch语句是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆