Comma as operator – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem! #CPP#1741 siteicon   siteicon   siteicon  

Problem Statement - Comma as operator

Comma is a sort of operator which can help form multiple instructions within same instruction.

Learning Objectives

  • Concept of comma operator.

TC++ #1741

#include <iostream.h>
#include <conio.h>
int main()
{
clrscr();
int x,y,z;
y=(x=5, ++x),x+=5;
z=((x=5, ++x),x+=5);
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
getch();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int x,y,z;
y=(x=5, ++x),x+=5;
z=((x=5, ++x),x+=5);
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
return 0;
}

Test it !

Solution


y=(x=5, ++x),x+=5;
Here y will be initialised with expression immediately following it within the round braces. Within the round braces is also a composite instruction using comma operator. Here x will be first initialised with 5 and then it will be immediately incremented. This will set y to value of 6. Immediately after comma after braces the another instruction will make value of x be added more with 5 and making it 11.

z=((x=5, ++x),x+=5);
Here since the whole RHS expression is in round braces, first inner braces will be evaluated making x as 6 and then 5 more will be added to x in the outer braces. This will make z to be filled with a value of 11.

Notes

  • Comma operator is useful when single line expression building is important, for e.g. while returning a value from a function. In usual cases multiple instruction lines may be more readable and maintainable as a program.


Suggested Filename(s): operator-comma.cpp, commaop.cpp



Share

CSKC| Created: 16-Dec-2017 | Updated: 28-Aug-2018|






Back