sequential-evaluation operation result

  • Thread starter Shivanand Kadwadkar
  • Start date
S

Shivanand Kadwadkar

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
 
I

Ike Naar

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;
 
S

Seebs

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top