这个C代码的输出是否依赖于编译器?

huangapple go评论71阅读模式
英文:

Is the output of this C code compiler dependent?

问题

变量 a 的值被更新了两次,这违反了C标准。因此,我认为这将取决于编译器。我在许多在线C编译器中运行了这段代码,它们都给出了相同的输出。

英文:
#include <stdio.h>

int main(void)
{ 
   int a = 0, b = 1;
   a = (a = 5) && (b = 0);
   printf("%d", a);
   printf("%d", b);
}

The value of variable a is getting updated twice, which violates the C standards. So I think it will be compiler dependent. My I ran this code in lot of online C compilers and all are giving same output.

答案1

得分: 8

这段代码的行为是由&&运算符引入的序列点所定义的。在C标准的第6.5.13p4节中明确规定了逻辑AND运算符&&的行为:

与按位二进制&运算符不同,&&运算符保证从左到右进行评估;**如果评估第二个操作数,则在评估第一个和第二个操作数之间存在一个序列点。**如果第一个操作数等于0,则不评估第二个操作数。

对于这段代码的分析:

a = (a = 5) && (b = 0);

首先评估&&运算符的左侧,即(a = 5),它将a设置为5。这评估为true,因此在右侧,即(b = 0)被评估之前存在一个序列点。这将b设置为0,并评估为false,因此&&运算符的结果为0。然后将这个值赋给a

英文:

The behavior of this code is well defined due to the sequence point introduced by the && operator. This is spelled out in section 6.5.13p4 of the C standard regarding the logical AND operator &&:

> Unlike the bitwise binary & operator, the && operator guarantees
> left-to-right evaluation; if the second operand is evaluated, there is
> a sequence point between the evaluations of the first and second
> operands.
If the first operand compares equal to 0, the second operand
> is not evaluated.

Going through the code:

a = (a = 5) && (b = 0);

The left side of the && operator, i.e. (a = 5) is evaluated first, which sets a to 5. This evaluates to true, so there is then a sequence point before the right side, i.e. (b = 0) is evaluated. This sets b to 0 and evaluates to false, so the && operator results in the value 0. This value is then assigned to a.

huangapple
  • 本文由 发表于 2023年6月8日 23:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定