5

I came across this block of code when studying for my class. It was in my professor's presentation and I thought it was an error, so out of pure curiosity, I tried to compile it. To my surprise, it's actually a valid code. I tried looking it up online but couldn't find a clear answer as to why exactly does it work.

int n, num;
scanf("%d", &n);
vector<int> arr;
arr.reserve(n);

while (n--)
        scanf("%d", &num),
        arr.push_back(num);

for (int i : arr) printf("%d ", i);
printf("\n");

I expected the while-loop to cause a compilation error, but it runs smoothly. Is it standard or was that introduced recently?

jaro2gw
  • 133
  • 8
  • Have you ever heard about [sequence operator](https://en.wikipedia.org/wiki/Comma_operator) (`,`)? ;-) – Scheff's Cat Apr 08 '19 at 08:08
  • 1
    It's the [comma operator](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) – Steve Apr 08 '19 at 08:08
  • 1
    It is called **comma operator**. My personal advice: In situations like that, always use braces. makes the code much clearer. – Davide Spataro Apr 08 '19 at 08:10
  • It's a bit tricky. In `f(12, 34);` the `,` is just a separator of arguments. But: `f((12, 34));` -> now the function has only one argument which is an expression consisting of a sequence of two expressions (with comma operator). – Scheff's Cat Apr 08 '19 at 08:11
  • While it's valid code, it's also *bad* code. It's confusing, hard to follow along, and for beginners will lead to all kinds of problems. That was a really bad thing of any professor to show their students. Even if it's a demonstration of the comma operator, it could have been done better IMO. – Some programmer dude Apr 08 '19 at 08:11

1 Answers1

3

This is the comma operator at work. It evaluates the left hand side of the operator (scanf("%d", &num)), then the right hand side (arr.push_back(num)) and returns the result of this expression.

I don't think the code snippet is a good usage scenario for the comma operator. It seems to be employed for not typing {} to create a body for the while loop, which is lazy and unnecessarily "smart". But it works.

If you're interested in legitimate use cases for the comma operator, have a look at this article.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • There is nothing better than straying from the lecture when you really should study xd For real tho thank you, I will check it out :D – jaro2gw Apr 08 '19 at 08:24