意外的结果,在GNU C三元运算符 [英] Unexpected Result, Ternary Operator in Gnu C

查看:175
本文介绍了意外的结果,在GNU C三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,在 C 三元运算符的运算符precedence似乎真正奇怪的我。案例分析:<​​/ P>

So the operator precedence of the ternary operator in C seems truly bizarre to me. Case in point:

#include <stdio.h>

int main ()
{
   int i=5;
   int j=6;
   int k=7;
   printf("A: %d\n", i+j+(k!=7)?1:11); //prints 1
   printf("B: %d\n", i+j+((k!=7)?1:11)); //prints 22
   return 0;
}

这似乎类似于这里的问题是:

<一href=\"http://stackoverflow.com/questions/7499400/c-ternary-conditional-and-assignment-operator-$p$pcedence\">C++三元条件和赋值运算符precedence

三元运算符的计算顺序

This seems similar to the question here:
C++ ternary conditional and assignment operator precedence
Ternary operator evaluation order

作为澄清,据我所知,括号使其工作,因为我的意见,我原来的职位说明...

As a clarification, I understand that the parentheses make it work, as my comments in my original post indicated...

我只是想知道,为什么语言的作者会选择的评价方法是这样的话可能会欺骗人了,当第一条语句似乎是它可以被格式化编译明智有效。

I'm just wondering why the language authors would pick an evaluation method that is so likely to trick people up, when the first statement seems like it could be formatted compiler-wise to be valid.

但随着在左侧或类成员中运营商的问题涉及,其中作为在RHS出现这种怪异的行为。

But those question deals with operators on the left-hand side or within class members, where as this weird behavior occurs on the RHS.

推荐答案

什么是奇怪的吗?第一部分是间preTED为:

What is weird here? The first part is interpreted as:

(11 + (k != 7)) ? 1 : 11

和第二个是间preTED为

and the second is interpreted as

 11 + ((k !=7) ? 1 :11)

首先是由precedence规则(二进制算术具有较高的precedence比三元运算符)而造成,第二通过与括号分组除权pression绕开precedence规则。

The first is caused by the precedence rules (binary arithmetic has higher precedence than the ternary operator) and the second circumvents the precedence rules through grouping the expression with parenthesis.

您的编辑要求的原因,一个通常只能在这些猜测,除非有人在C委员会谁是present当时恶有恶报帮助。我的猜测是,它是更为普遍的是使用一个复杂的前pression并要求比使用三元运算符来确定的算术一位前pression价值的真值。像这样的东西浮现在脑海:

Your edit asks for the reasons and one can usually only guess at those unless someone on the C committee who was present at the time comes around to help. My guess would be that it is much more common to use a complex expression and ask for its truth value than using the ternary operator to determine the value of an expression in arithmetic. Something like this comes to mind:

return (froble() + 3) == 0 ? 23 : 5; // parens for sanity but works without

如果这将是PTED为间$ P $回报(froble()+ 3)== 5; 我会深感震惊。

if this would be interpreted as return (froble() + 3) == 5; I would be truly shocked.

这篇关于意外的结果,在GNU C三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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