How does the Comma Operator work

Question :

How does the Comma Operator work,

Answer :

How does the comma operator work in C++?

For instance, if I do:

a = b, c;    

Does a end up equaling b or c?

(Yes, I know this is easy to test – just documenting on here for someone to find the answer quickly.)

Update: This question has exposed a nuance when using the comma operator. Just to document this:

a = b, c;    // a is set to the value of b!    a = (b, c);  // a is set to the value of c!  

This question was actually inspired by a typo in code. What was intended to be

a = b;  c = d;  

Turned into

a = b,    //  <-  Note comma typo!  c = d;  


Take care to notice that the comma operator may be overloaded in C++. The actual behaviour may thus be very different from the one expected.

Read More  How can I run a Windows GUI application on as a service?

As an example,uses the comma operator quite cleverly to implement list initializers for symbol tables. Thus, it makes the following syntax possible and meaningful:

keywords = "and", "or", "not", "xor";  

Notice that due to operator precedence, the code is (intentionally!) identical to

(((keywords = "and"), "or"), "not"), "xor";  

That is, the first operator called is keywords.operator =("and") which returns a proxy object on which the remaining operator,s are invoked:

keywords.operator =("and").operator ,("or").operator ,("not").operator ,("xor");  

That's the answer How does the Comma Operator work, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Read More  Should I avoid using Java Label Statements?

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you