Explain the use of comma operator with example.


 The comma operator in programming languages allows you to evaluate multiple expressions in a single statement, separated by a comma. The expressions are evaluated from left to right, and the value of the last expression is returned.

Here's an example in C++:

css
int a = 1, b = 2, c = 3; int sum = (a += 1, b += 2, c += 3, a + b + c);

In this example, we declare and initialize three variables a, b, and c. We then use the comma operator to increment each of these variables by 1, 2, and 3, respectively, and finally compute the sum of all three variables.

Note that the expressions inside the parentheses are evaluated from left to right, and the value of the last expression (a + b + c) is returned and assigned to the variable sum. So, the value of sum will be 10, which is the sum of a, b, and c after they have been incremented.

The comma operator can also be used in a loop, where multiple expressions need to be evaluated at each iteration. For example:

c
for (int i = 0, j = 10; i < j; i++, j--) { cout << "i = " << i << ", j = " << j << endl; }

In this example, we use the comma operator to initialize and update two loop variables i and j at each iteration of the loop. The loop will continue as long as i is less than j. Inside the loop, we print the current values of i and j.

Post a Comment

Previous Post Next Post