C/Regarding program
Expert: Zlatko - 11/22/2011
QuestionHi Sir,
I want to ask a question regarding a program.Please help me out of this.i want you to resolve this query.
void main()
{
int a=10,b=20;
char x=1,y=0;
if(a,b,x,y)
{
printf("exam");
}
AnswerHi Abhishek
If you have 2 expressions, separated by a comma, like this: e1,e2 the program first evaluates e1, then e2, and the result of the entire line e1,e2 is the result of evaluating e2.
For example
int a=10;
int y=20;
int r;
a,y;
first, a is evaluated. It is 10, then y is evaluated, it is 20, so the result of a,y is 20. If you assign the result to r, like this r = (a,y); you find that r is 20.
However, there is a subtle point. The comma has a lower precedence than assignment, so if you write
r=a,y
r gets 10, because the assignment is done first.
If you write
r=(a,y)
you force the comma operator to be done first, and r gets 20.
All this means that in your program, the expression
(a,b,x,y)
returns the value of y, which is 0, so exam is not printed.
So what is the point? Why not write r=y, or in your case, if(y). Well, using the comma operator only makes sense if the expressions have some side effects, like calling a function, or changing a value. Even so, there are usually cleaner ways of writing the code.
The comma operator is almost never used. The only use for it I've seen is in for loops where you can use it to do multiple initialization and modification of loop counters, like this:
int main()
{
int a;
int b;
int c = 0;
int d = 0;
for(a=1, b=2; b<10; a+=1, b+=2)
{
printf("a:%d b:%d\n", a, b);
}
}
If you run this program, you see variable 'a' being incremented by 1, and 'b' being incremented by 2 as expected. Those are the "side-effects".
To convince yourself that the comma is an operator returning the value of the second expression, you can try this:
int main()
{
int a;
int b;
int c = 0;
int d = 0;
for(a=1, b=2; b<10; a+=1, b+=2)
{
printf("a:%d b:%d\n", a, b);
}
printf("\n");
for(d = (a=1, b=2); b<10; c = (a+=1, b+=2))
{
printf("d:%d a:%d b:%d, c:%d\n", d, a, b, c);
}
}
and you will see that both d and c get the value of the last expression in the comma list.
I hope that makes things clear.
Best regards
Zlatko