需要输出说明 [英] Require explanation for the output

查看:106
本文介绍了需要输出说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

#include<stdio.h>
int main()
{
    int j = 7, i = 4;
    j = j || ++i && printf("you can");
    printf("%d %d",i,j);
    return 0;
}

输出: 4 1

[代码链接] [1]

[Code Link][1]

  1. 前缀运算符的优先级高于逻辑运算符. 2.逻辑&&的优先级高于逻辑||.
  2. 在逻辑AND(&&)中,如果第一个操作数的计算结果比第二个错误,则不计算;在逻辑OR(||))中,如果第一个操作数的计算结果为true,则第二个值将不计算.
  3. 完整表达式的计算结果为true,因此j为1.
  1. The precedence of prefix operator is higher than logical operators. 2.Logical && has higher precedence than logical ||.
  2. In Logical AND(&&) if first operand evaluates to false than second will not be evaluated and In Logical OR(||) if first operand evaluates to true, then second will not be evaluated.
  3. The complete expression is evaluating to true, therefore j is 1 .

疑问:

  1. 为什么这里没有遵循第一个规则?不是吗?

  1. Why the first rule is not followed here? Shouldn't it be correct?

j=(j||((++i) &&printf("you can")));

因此,在printf语句中,i的值变为5.

Therefore value of i becomes 5, in the printf statement.

为什么这里违反了通用优先规则?当两个运算符的优先级相同时,关联性将起作用.编译器是否应该首先查看要评估||还是&&?

Why are the general precedence rules are violated here? Associativity comes into action when precedence of two operators is same. Shouldn't the compiler first see whether to evaluate || or &&?

如果首先评估||,而不是据我所知,那么结果是正确的.但是,如果不首先评估它,则应该打印can51.

If || is evaluated first, which shouldn't be as per my knowledge, then result is correct. However, if it is not evaluated first, then you can51 should be printed.

推荐答案

在此表达式中:

j = j || ++i && printf("you can");

||之后有一个序列点,并且从左到右进行评估.由于j为非零值,因此不对表达式的其余部分求值.因此,j || (....)变为1.由于未评估++i,所以我仍然为4.因此,输出为4, 1.

There's a sequence point after the || and it is evaluated from left to right. Since j is non-zero, the rest of the expression is not evaluated. Hence, j || (....) becomes true which is 1. Since is ++i is not evaluated i remains 4. Hence, the output is 4, 1.

根据C标准:

附件C

-以下运算符的第一个操作数的结尾:逻辑AND && (6.5.13);逻辑或|| (6.5.14);有条件的? (6.5.15);逗号, (6.5.17).

— The end of the first operand of the following operators: logical AND && (6.5.13); logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).

如果j为零,则将评估++i && printf("you can"),并且i将变为5,并且还将打印you can.您对++的优先级大于||是正确的,但是由于存在序列点,因此首先会忽略j||.

If you j was zero then ++i && printf("you can") would have been evaluated and i would become 5 and you can will also be printed. You are correct about the precedence of ++ being greater than ||, but since there's a sequence point, j|| is evalauted first.

这篇关于需要输出说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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