Velocity Reviews > sequential-evaluation operation result

# sequential-evaluation operation result

Guest
Posts: n/a

 01-01-2011
I far i know sequential-evaluation operator are evaluated from left
and right and it will only take the right most result

#include<stdio.h>
int main()
{
int i=0,j=2,k=5;
int ans1,ans2;

ans1=(i,j,k); // Evaluated from left to right and we assign 5 to ans1
ans2=i,j,k; // Why it is not same here that we assign 5 to ans2
printf("ans1 %d ans2 %d \n",ans1,ans2);

return 0
}
Output:
ans1 5 ans2 0
-------------------------------------------------

My doubt is with ans2, is comma treated as separator here and we
discard the right value and take only the left one

Ike Naar
Guest
Posts: n/a

 01-01-2011
On 2011-01-01, Shivanand Kadwadkar <(E-Mail Removed)> wrote:
> int i=0,j=2,k=5;
> int ans1,ans2;
>
> ans1=(i,j,k); // Evaluated from left to right and we assign 5 to ans1
> ans2=i,j,k; // Why it is not same here that we assign 5 to ans2

``='' binds stronger than ``,'' so the last expression is parsed as

(ans2=i),j,k;

Seebs
Guest
Posts: n/a

 01-01-2011
On 2011-01-01, Shivanand Kadwadkar <(E-Mail Removed)> wrote:
> I far i know sequential-evaluation operator are evaluated from left
> and right and it will only take the right most result

No, you don't. You just said something totally incoherent.

> ans1=(i,j,k); // Evaluated from left to right and we assign 5 to ans1

There is no left-to-right or right-to-left.

Evaluation is not the same thing as *grouping*. What is relevant here
is that you have an assignment of
ans1
=
(i,j,k)

> ans2=i,j,k; // Why it is not same here that we assign 5 to ans2

Because here, you have
ans1=i
j
k

Which is to say, commas have lower precedence than equals signs; the
expressions separated by commas can be assignment expressions including
equals signs, so instead of assigning the value "i,j,k" to ans1, you're
assigning the value "i" for your first expression, then j, then k.

What you may be missing is that in C, assignment is just another kind
of expression, not a "statement" or something.

> My doubt is with ans2, is comma treated as separator here and we
> discard the right value and take only the left one

The word "doubt" is not correct here in standard English. A "doubt"
is where someone told you something and you don't believe them.

Anyway, C generally doesn't specify order of evaluation. Comma operators
are special in that they do, but "order of evaluation" is totally
distinct from "grouping".

-s
--
Copyright 2010, all wrongs reversed. Peter Seebach / http://www.velocityreviews.com/forums/(E-Mail Removed)
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.