简体   繁体   English

在 C 编程语言中:将 3(数字 3)分配给变量的顺序是什么? 至于哪个变量会收到 3 第一,第二和第三?

[英]In C programming Language: What order would 3 (Number 3) be assigned to the variables? As in which variable would receive 3 first, second and third?

运算符的结合性Question Continued: In C programming Language: For the Question below: What order would 3 (Number 3) be assigned to the variables?问题续:在 C 编程语言中:对于下面的问题:将 3(数字 3)分配给变量的顺序是什么? As in which variable would receive 3 first, second and third?哪个变量将接收 3 第一、第二和第三? And which variable would have 3 in the end?最终哪个变量会有 3?

Question: A = B = C = 3问题: A = B = C = 3

Further explanation of What I'm asking/My attempts to understand this concept:进一步解释我在问什么/我试图理解这个概念:

According to the image I've attached stating the Associativity of Operators, the Assignment operators should be from left to right no?根据我附上的说明运算符结合性的图像,赋值运算符应该从左到右不是吗?

So should 3 be assigned to A, then B, and then C?那么应该将 3 分配给 A,然后是 B,然后是 C?

According to a practice question solution it is the opposite, 3 being assigned to C, then B, then A, so am very confused why it's right to left?根据练习题的答案是相反的,3 被分配给 C,然后是 B,然后是 A,所以我很困惑为什么它是从右到左的? When the Associativity of Operators say it's left to right!当运算符的结合性说它是从左到右时!

The expression A = B = C = 3 is parsed in C as A = (B = (C = 3)) .表达式A = B = C = 3在 C 中被解析为A = (B = (C = 3)) The assignment operator associates right-to-left.赋值运算符从右到左关联。

However, the actual assignment is specified as a side effect of the expression, and the order in which these side effects occur is not specified by the C standard.但是,实际赋值被指定为表达式的副作用,而这些副作用发生的顺序并未由 C 标准指定。

The image in the question is wrong to show the order of assignment operators as left to right, and the source of the image should be regarded with suspicion.问题中的图像将赋值运算符的顺序显示为从左到右是错误的,应该怀疑图像的来源。 The association of assignment operators arises out of the grammar rules in the C standard, where 6.5.16 shows one rule as:赋值运算符的关联源于 C 标准中的语法规则,其中 6.5.16 显示了一个规则:

assignment-expression : unary-expression assignment-operator assignment-expression赋值表达式一元表达式赋值运算符赋值表达式

The fact that the right operand is an assignment expression means that in X = Y , Y can be another assignment expression, such as Z = 4 , but X cannot be.右操作数是赋值表达式这一事实意味着在X = YY可以是另一个赋值表达式,例如Z = 4 ,但X不能。 So A = B = C = 3 must be parsed as C = 3 being an assignment expression inside of B = … , and B = C = 3 must be an assignment expression inside of A = … .所以A = B = C = 3必须被解析为C = 3B = …内部的赋值表达式,而B = C = 3必须是A = …内部的赋值表达式。 Contrast this with a rule for one of the additive operators in C 6.5.6:将此与 C 6.5.6 中的加法运算符之一的规则进行对比:

additive-expression : additive-expression - multiplicative-expression加法表达式加法表达式-乘法表达式

In that rule, the additive-expression is on the left, so A - B - C necessarily groups as (A - B) - C .在该规则中,附加表达式在左侧,因此A - B - C必须分组为(A - B) - C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM