C / C ++ Syntax - Separating statements instead; legally?

I just came across this piece of code that does this:

delete a, a = 0; 

It compiles and works fine. But shouldn't it be:

 delete a; a = 0; 

Why is the separation of statements using allowed in this case?

Thanks:)

+7
source share
5 answers

This is a comma. It evaluates both arguments and returns the second.

+6
source

In C and C ++, most of the "statements" are actually expressions. A semicolon added to an expression turns it into an operator. As an alternative, (but almost always bad) separation of side effects using the comma operator is allowed: the left expression is evaluated by its side effects (and its value is discarded), and the right -side expression is evaluated by its value.

+7
source

This is a comma operator. It can be used to separate expressions, but not declarations.

+5
source

This is a comma operator . MSDN article here . And look at this question to understand how it works.

+5
source

Although you can write code like this, it can be somewhat strange. A slightly more realistic usecase would be if you have a T structure as follows:

 struct T { bool check() const; void fix(); }; 

Now you want to iterate over everything in the structure and run a check on it, and then call fix if check returns false. An easy way to do this would be

 for (list<T>::iterator it = mylist.begin(); it < mylist.end(); ++it) if (!it->check()) it->fix(); 

Suppose you want to record it as short as possible. fix() return void means you cannot just put it in a state. However, using a comma, you can get around this:

 for (auto it = mylist.begin(); it != mylist.end() && (it->check() || (it->fix(), true)); ++it); 

I would not use it without much reason, but this allows you to call any function from a condition that may be convenient.

+1
source

All Articles