Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma operators in c++

Tags:

c++

int main() {
   int x = 6;
   x = x+2, ++x, x-4, ++x, x+5;
   std::cout << x;
}

// Output: 10

int main() {
   int x = 6;
   x = (x+2, ++x, x-4, ++x, x+5);
   std::cout << x;
}

// Output: 13

Please explain.

like image 388
Gautam Kumar Avatar asked Sep 14 '11 17:09

Gautam Kumar


People also ask

How to use the comma in C/C++?

In C or C++, the comma ‘,’ is used in different purposes. Here we will see how they can be used. Comma as an Operator. The comma operator is a binary operator, that evaluates its first operand, and then discards the result, then evaluates the second operand and returns the value. The comma operator has the lowest precedence in C or C++.

How can the result of the comma operator be used?

The comma operator is lower precedence than assignment. All expressions in a comma operator are evaluated, but only the last is used as the resulting value. So both assignments are performed. The result of the comma operator in your case would be the result of c = d. This result is not used. Can you show that how can the result be used?

What is comma operator in C++ instead of semicolon?

3) Comma operator in place of a semicolon. We know that in C and C++, every statement is terminated with a semicolon but comma operator also used to terminate the statement after satisfying the following rules. The variable declaration statements must be terminated with semicolon.

What programming languages have commas in them?

In the OCaml and Ruby programming languages, the semicolon (";") is used for this purpose. JavaScript and Perl utilize the comma operator in the same way C/C++ does. In Java, the comma is a separator used to separate elements in a list in various contexts.


1 Answers

Because , has lower precedence than =. In fact, , has the lowest precedence of all operators.

First case:

x=x+2,++x,x-4,++x,x+5;

This is equivalent to

(x=x+2),(++x),(x-4),(++x),(x+5);

So, x becomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that is x-4 value is calculated and discarded, then increment again, now x is 10, and finally, another no-op. x is 10.

Second case:

x=(x+2,++x,x-4,++x,x+5);

This is equivalent to

x=((x+2),(++x),(x-4),(++x),(x+5));

x+2 is calculated, then x is incremented and becomes 7, then x - 4 is calculated, then x is incremented again and becomes 8, and finally x+5 is calculated which is 13. This operand, being the rightmost one, is the taken as the result of the whole comma expression. This value is assigned to x.
x is 13.

Hope it's clear.

And, as one of the comments suggests -

NEVER WRITE CODE LIKE THIS

like image 85
Armen Tsirunyan Avatar answered Sep 27 '22 20:09

Armen Tsirunyan