4

Consider this "EXAM" question:

int main()
{
   int a=10,b=20;
   char x=1,y=0;
   if(a,b,x,y)
   {
      printf("EXAM");
   }
}

Please let me know why this doesn't print anything at all.

1
  • 1
    Hi Gollum, I'm surprised to see you here. Anyway, for me the output isn't "Printed Nothing" and I don't see a C question being outputted either... Commented May 14, 2010 at 10:41

5 Answers 5

11

Comma operator - evaluates 1st expression and returns the second one. So a,b,x,y will return value stored in y, that is 0.

Sign up to request clarification or add additional context in comments.

Comments

3

The result of a,b,x,y is y (because the comma operator evaluates to the result of its right operand) and y is 0, which is false.

Comments

2

The comma operator returns the last statement, which is y. Since y is zero, the if-statement evaluates to false, so the printf is never executed.

Comments

1

Because expression a,b,x,y evaluates to y, which in turn evaluates to 0, so corresponding block is never executed. Comma operator executes every statement and returns value of last one. If you want logical conjunction, use && operator:

if (a && b && x && y) { ... }

Comments

0

Others already mentioned that the comma operator returns the right-most value. If you want to get the value printed if ANY of these variables is true use the logical or:

int main()
{
   int a=10,b=20;
   char x=1,y=0;
   if(a || b || x || y)
   {
      printf("EXAM");
   }
 }

But then be aware of the fact that the comma evaluates all expressions whereas the or operator stops as soon as a value is true. So with

int a = 1;
int b;
if(a || b = 1) { ... }

b has an undefined value whereas with

int a = 1;
int b;
if(a, b = 1) { ... }

b will be set to 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.