When is it advisable to use a comma to separate two or more conditions in C ++?

I recently discovered that this is a valid C ++ syntax:

int bar = 0;
for(int foo = 0; bar = 0, foo != 10; foo++)
{
    //some code
}

I have not seen a comma used before as a separator of two conventions, so I looked at how this works.

I found that when separating the list of conditions with commas, they are all satisfied, but only the latter is used as a condition. For example:

while(function1(), function2(), function3())
{
    //code
} 

Here functions 1, function2 and function3 will be executed every time through a loop. However, to determine whether to continue the loop, only the return value of the function3 will be used.

My question is: are there any situations in which this is best done?

For me it makes sense:

while(function3())
{
    function1();
    function2();

    //some code
} 

When would it be appropriate to use commas instead to separate conditions?

+4
3

, : , , .

, , . , , , , ( ). Comma , . , , , .

, . , , .

, , , (, for), .

, ,

for (ListItem* ptr = list_header; 
     assert(ptr != NULL), ptr->key != target_key;
     ptr = ptr->next);

, target_key (.. ). -.

while(function1(), function2(), function3()) , function3() function1(), function2(). , , , , , while . while(function1(), function2(), function3()),

do 
{
  function1();
  function2();
  if (!function3())
    break;
  ...
} while (true);
+8

, . :

for(int foo = 0; bar = 0, foo != 10; foo++)

, :

for(int foo = 0, bar = 0; foo != 10; foo++)

for(int foo = 0; bar == 0, foo != 10; foo++)

( , , , bar == 0 ).

+2

, , .

In any case, each situation should be considered separately to confirm that such a design is optimal.

+1
source

All Articles