This question already has answers here:
What does the comma operator , do? (9 answers)
Closed6 years ago.
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;- 1The second code snippet is not balanced - there are three opening
{s and two closing}s - it is missing a}.Peter Mortensen– Peter Mortensen2019-05-11 22:53:17 +00:00CommentedMay 11, 2019 at 22:53 - See also here:stackoverflow.com/questions/16475032/…Valentino– Valentino2019-05-11 23:07:47 +00:00CommentedMay 11, 2019 at 23:07
1 Answer1
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
387k77 gold badges670 silver badges1.1k bronze badges
Sign up to request clarification or add additional context in comments.
20 Comments
Gilad
ohh god, why why why would anyone write this code. Thanks
Lightness Races in Orbit
@Gilad Trying to be clever, most likely! And failing.
Andrey Sv
@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.
Deduplicator
Of course, that hack is especially useful for macros, which one also should avoid assiduously.
Lightness Races in Orbit
@AndreySv Such programmers have had some thirty years to break that habit, i.e. since before C++ even existed.
|
Explore related questions
See similar questions with these tags.


