三元运算符的奇怪枚举行为 [英] Strange enum behavior with ternary operators

查看:64
本文介绍了三元运算符的奇怪枚举行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用我的一个枚举编写一个非常简单的三元运算符,但我偶然发现了一个非常奇怪的错误(对我来说).给出这段代码:

I was writing a very simple ternary operator with one of my enum and I stumbled upon what is a very strange error (to me..). Given this piece of code:

typedef enum
{
    first = 0,
    second,
    last
}myEnum;

myEnum myVar = first;

(myVar < second) ? myVar++ : myVar = last;

编译器向我发送了以下错误:

The compiler sent me the following error:

错误:左值必须作为赋值的左操作数

error: lvalue required as left operand of assignment

就像我只是简单地将三元数更改为if/else这样:

Where as if I simply change the ternary to a if/else block like this :

if(myVar < second)
{
    myVar++;
}
else
{
    myVar = last;
}

所有内容均可编译并正常运行.有人可以解释为什么不能编译为三进制的完全相同的代码吗?我想念什么?

Everything compiles and works fine. Can somebody explain why the exact same code written as a ternary won't compile? What am I missing?

推荐答案

您的表达式被解析为:

( (myVar < second) ? myVar++ : myVar ) = last;

但是您似乎打算这样做:

but you seem to have intended to do:

(myVar < second) ? myVar++ : (myVar = last);

这实际上不是标准所要求的(但是许多编译器以这种方式解析),第一个表达式实际上应该由于其他原因(语法错误而不是违反约束)而失败.

This is actually not exactly what the standard mandates (but many compilers parse it that way), the first expression should actually fail for another reason (a syntax error rather than a constraint violation).

C99 6.5.15说:

C99 6.5.15 says:

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

myVar = last 不是条件表达式,而是赋值表达式(C99 6.5.16):

and myVar = last is not a conditional-expression but an assignment-expression (C99 6.5.16):

assignment-expression:
    conditional-expression
    unary-expression assignment-operator assignment-expression

但是(myVar<秒)?myVar ++:myVar 不是 unary-expression (请参阅C99 6.5.3)(但其括号内的版本应该是,如我在第一个代码段中所写,请参阅C99 6.5).1).

but (myVar < second) ? myVar++ : myVar is not an unary-expression (see C99 6.5.3) (but the parenthesized version thereof would be, that is as I wrote in my first code snippet, see C99 6.5.1).

HTH

这篇关于三元运算符的奇怪枚举行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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