Quiz on Comma Operators in C

Quiz on Comma Operators in C | This operator allows the evaluation of multiple expressions, separated by the comma, from left to right in order, and the evaluated value of the rightmost expression is excepted as the final result.

Syntax:- variable = (expression1, expression2, ......., expresionN);

The comma operator allows us to evaluate multiple expressions whenever a single expression is allowed. The comma operator evaluates to its rightmost operand.

If you finding difficulties to solve these questions then first you should learn these:- Operators in CBitwise operators in C

Comma Operators Quiz in C

Find out the output of the programs given in Quiz on Comma Operators in C?

Q1) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int i = 1;
  int j ;
  j = (i=i+8, i%5);
  printf("%d",j);
  return 0;
}

a) 9
b) 0
c) 4
d) 1

View Answer Answer:- c) 4

Given expression from left i=i+8=1+8=9 gives i=9. Now, 2nd expression i%5=9%5=4. Finally j=4.

Q2) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int a=2, b=3, c;
  c=a, a=b, b=c;
  printf("%d %d %d",a,b,c);
  return 0;
}

a) None of these
b) 3 2 3
c) 3 2 2
d) 2 3 2

View Answer Answer:- c) 3 2 2

Q3) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int i = 0;
  int j ;
  j = (i=i+1, i=i+2, i=i+3);
  printf("%d",j);
  return 0;
}

a) 2
b) 3
c) 6
d) 1

View Answer Answer:- c) 6

Given expressions evaluated from left to right, i=i+1 gives i=1; 2nd expression i=i+2=1+2=3 gives i=3; 3rd expression i=i+3=3+3=6 gives i=6. The comma operator evaluates to it’s rightmost operand.

Q4) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int a;
  a = 0, 1;
  printf("%d",a);
  return 0;
}

a) Garbage value
b) Compile time error
c) 0
d) 1

View Answer Answer:- c) 0

The comma operator evaluates to its rightmost operand.

Q5) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int a;
  a = (0, 1);
  printf("%d",a);
  return 0;
}

a) 1
b) Garbage value
c) 0
d) Compile time error

View Answer Answer:- a) 1

Here () is used so expressions evaluated from left to right, and so a=1

Q6) Find the output of the given C program.

#include<stdio.h>
int main()
{
  int a = 0, 1;
  printf("%d",a);
  return 0;
}

a) Garbage value
b) Compile time error
c) 0
d) 1

View Answer Answer:- b) Compile time error

Compile time error; Error due to int a=0,1; invalid declaration of variable.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *