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.
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
