开发者

Confusion with Associativity of Assignment operator in C

As we all know that Associativity of assignment operator is from right to left but in the given code output should be zero if we go from right to left but output is 1 .

 main()
 {
 int a=3,b=2;
 a=a==b==0;
 printf("%d",a);
 }

How output is coming out to be 1 if we go by right to letf??

If we go by right to left then (b==0) should be Evaluat开发者_C百科ed first and gives result 0 and then expression (a==0) is Evaluated also gives 0 and at last a's value will be 0.


Assignment is done RTL, but equality (==) isn't.

The statement is actually:

a = ((a == b) == 0)

The right hand side of the assignment is evaluated from left to right. In steps, this is what's happening:

  1. a == b is 0
  2. 0 == 0 is 1
  3. 1 is assigned to a


Your code is equivalent to :

a = ((a == b) == 0);


Note, this is phrased this way as it was merged from this question. OP asked why a==b==c is equivalent to a==b && b==c in Objective C (which is a strict superset of C). I asked this answer to be migrated since it cites the specificatio where other answers here do not.


No, it is not, it's like (a==b) == c.

Let's look at a simple counter example to your rule:

(0 == 0 == 0);// evaluates to 0

However

(0 == 0) && (0 == 0) // evaluates to 1

The logic is problematic since:

(0 == 0 == 0) reads out as ((0 == 0) == 0) which is similar to 1 == 0 which is false (0).


For the ambitious student

A little dive on how this is evaluated. Programming languages include grammar which specifies how you read a statement in the language. Siance Objective-C does not have an actual specification I'll use the C specificification since objective-c is a strict superset of c.

The standard states that an equality expression (6.5.9) is evaluated as the following:

Equality Expression:

relational-expression

equality-expression == relational-expression

equality-expression != relational-expression

Our case is the second one, since in a == b == c is read as equality_expression == relational_expression where the first equality expression is a == b.

(Now, the actual result number follow quite a way back to a number literal, equality->relational->shift->additive->multiplicative->cast->unary->postfix->primary->constant , but that's not the point)

So the specification clearly states that a==b==c does not evaluate the same way as a==b && b==c

It's worth mentioning that some languages do support expressions in the form a<b<c however, C is not one such language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜