C和C之间的条件运算差异++ [英] Conditional operator differences between C and C++

查看:100
本文介绍了C和C之间的条件运算差异++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的地方,在:用C 运营商在C ++中略有不同,即有一些源$ C ​​$ C这两种语言的工作方式不同。不幸的是,我找不到任何地方的文本。有谁知道这有什么区别?

I read somewhere that the ?: operator in C is slightly different in C++, that there's some source code that works differently in both languages. Unfortunately, I can't find the text anywhere. Does anyone know what this difference is?

推荐答案

在C中的条件运算符++可以返回一个左值,而C不容许类似的功能。因此,以下是在C ++中合法的:

The conditional operator in C++ can return an lvalue, whereas C does not allow for similar functionality. Hence, the following is legal in C++:

(true ? a : b) = 1;

在C复制,你将不得不求助于的if / else,或直接处理引用:

To replicate this in C, you would have to resort to if/else, or deal with references directly:

*(true ? &a : &b) = 1;

此外,在C ++中, = 运营商拥有的等于precedence和组从右到左的选择,例如:

Also in C++, ?: and = operators have equal precedence and group right-to-left, such that:

(true ? a = 1 : b = 2);

是有效的C ++ code,但会抛出C中的错误,而不绕前最后pression括号:

is valid C++ code, but will throw an error in C without parentheses around the last expression:

(true ? a = 1 : (b = 2));

这篇关于C和C之间的条件运算差异++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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