三元条件和赋值运算符优先级 [英] Ternary conditional and assignment operator precedence

查看:236
本文介绍了三元条件和赋值运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑直接赋值和三元条件运算符优先级:

I'm confused about direct assignment and ternary conditional operators precedence:

#include<stdio.h>
int main(void)
{
    int j, k;

    j = k = 0;
    (1 ? j : k) = 1; // first
    printf("%d %d\n", j, k);

    j = k = 0;
    1 ? j : k = 1; // second
    printf("%d %d\n", j, k);
    return 0;
}



我希望输出为:

I would expect the output to be:

1 0
1 0

但它恰好是:

1 0
0 0

此外,我收到此警告:


cpp:20:warning:语句没有效果

main.cpp:20: warning: statement has no effect

这是关于我评论为第二行的行。

which is about the line I commented as second.

由于直接赋值运算符的优先级比三元条件运算符的优先级低,我希望将第一和第二行注释为等价。

Since the direct assignment operator has less precedence than the ternary conditional operator, I was expecting lines commented as first and second to be equivalent. But alas it is not the case.

我试过这个与g ++ --version(Ubuntu 4.4.3-4ubuntu5)4.4.3

I tried this with g++ --version (Ubuntu 4.4.3-4ubuntu5) 4.4.3

推荐答案

C / C ++语言中的运算符优先级未由表或数字定义,而由语法定义。以下是来自 C ++ 0x草稿 chapter 5.16条件运算符[expr.cond]

The operator precedence in the C/C++ language in not defined by a table or numbers, but by a grammar. Here is the grammar for conditional operator from C++0x draft chapter 5.16 Conditional operator [expr.cond]:


conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression

优先级表如这一个因此是正确的,当你使用分配在双核的左侧,但不是当使用在右侧。这不对称的原因是什么我不知道。这可能是一个历史原因:在C中,条件结果不是左值,因此赋值它是没有意义的,允许赋值被接受没有括号可能看起来聪明在那个时候。

The precedence table like this one is therefore correct when you use assignment on the left side of the doublecolon, but not when used on the right side. What is the reason for this asymmetry I have no idea. It may be a historical reason: in C the conditional result was not lvalue, therefore assigning something to it had no sense, and allowing assignment to be accepted without parentheses might seem smart at that time.

这篇关于三元条件和赋值运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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