三元运算符为什么以及何时返回左值? [英] Why and when does the ternary operator return an lvalue?

查看:59
本文介绍了三元运算符为什么以及何时返回左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很长一段时间我都认为三元运算符总是返回一个右值.但令我惊讶的是它没有.在下面的代码中,我没有看到 foo 的返回值和三元运算符的返回值之间的区别.

For a long time I thought that the ternary operator always returns an rvalue. But to my surprise it doesn't. In the following code I don't see the difference between the return value of foo and the return value of the ternary operator.

#include <iostream>
int g = 20 ;

int foo()
{
    return g ;
}

int main()
{
    int i= 2,j =10 ;

    foo()=10 ; // not Ok 
    ((i < 3) ? i : j) = 7; //Ok
    std::cout << i <<","<<j << "," <<g << std::endl ;
}

推荐答案

ij 都是 glvalues(参见 此值类别参考 了解详情).

Both i and j are glvalues (see this value category reference for details).

如果你阅读了这个条件运算符参考要点:

4) 如果 E2 和 E3 是相同类型和相同值类别的泛左值,则结果具有相同类型和值类别

4) If E2 and E3 are glvalues of the same type and the same value category, then the result has the same type and value category

那么 (i <3) 的结果是什么?i : j 是一个泛左值,可以赋值给.

So the result of (i < 3) ? i : j is a glvalue, which can be assigned to.

然而,我真的不推荐这样做.

However doing something like that is really not something I would recommend.

这篇关于三元运算符为什么以及何时返回左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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