26

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 theif()?

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;
askedMay 11, 2019 at 20:44
Gilad's user avatar
2
  • 1
    The second code snippet is not balanced - there are three opening{s and two closing}s - it is missing a}.CommentedMay 11, 2019 at 22:53
  • See also here:stackoverflow.com/questions/16475032/…CommentedMay 11, 2019 at 23:07

1 Answer1

31

The programmer has used thecomma operator to provide two unrelated expressions in a single statement. Because it's a single statement, both expressions are "inside" theif 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;}
answeredMay 11, 2019 at 20:46
Lightness Races in Orbit's user avatar
Sign up to request clarification or add additional context in comments.

20 Comments

ohh god, why why why would anyone write this code. Thanks
@Gilad Trying to be clever, most likely! And failing.
@LightnessRacesinOrbit This is a habit of old school programmers due to small monitor resolution (25 rows 80 columns) code was writing as short as possible. More code on one page better readability. Try read modern code on such monitor and you will see how many empty rows in it.
Of course, that hack is especially useful for macros, which one also should avoid assiduously.
@AndreySv Such programmers have had some thirty years to break that habit, i.e. since before C++ even existed.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.