Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a comma mean inside an 'if' statement? [duplicate]

Tags:

Consider:

for (auto i = 0; i < g.size(); ++i)     for (auto j = 0; j < g.size(); ++j) if (g[i][j] == 0) dfs(g, i, j), ++regions; return regions; 

I don't like one line code. What does the code execute in the if()?

I am confused by the "," sign.

Usually I would write it as:

  for (auto i = 0; i < g.size(); ++i)   {       for (auto j = 0; j < g.size(); ++j)       {           if (g[i][j] == 0)           {              dfs(g, i, j)           }           ,++regions; // I am not sure what to do here. Inside the "if" scope??       } }    return regions; 
like image 348
Gilad Avatar asked May 11 '19 20:05

Gilad


People also ask

What is the purpose of the comma operator?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What does comma mean in binary?

The comma operator (represented by the token, ) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type).

What is the purpose of comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

Do while loops use commas?

The comma operator evaluates both of its arguments in turn, throwing away the result, except for the last. The last evaluated expression determines the result of the entire expression. i<=8,i++ - here the value of the expression is the value of i++ , which is the value of i before being incremented.


1 Answers

The programmer has used the comma operator to provide two unrelated expressions in a single statement. Because it's a single statement, both expressions are "inside" the if condition.

It's a poor hack, which would be better done with actual {} braces surrounding two statements.

Your example is not equivalent; it should be:

if (g[i][j] == 0)  {    dfs(g, i, j);    ++regions; } 
like image 106
Lightness Races in Orbit Avatar answered Sep 16 '22 14:09

Lightness Races in Orbit