2

fast question what does this do in c++;

auto asd = (1,2,3,4,5);

note: this does note emit an error

Is this a class? If it is a struct of data or class or array, can you tell me how to get the individual element value;

When i cout << asd ; It return always the last number, in this case 5

thanks in advance

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Ignore the parenthesis, they don't do anything here. You are invoking the comma operator on `int`s, ergo you return the final value from the expression. – Mansoor Sep 17 '19 at 12:27
  • what a nice application of my most favourite tool for obfuscation :) – 463035818_is_not_an_ai Sep 17 '19 at 12:27
  • It invokes the comma operator, https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work – divinas Sep 17 '19 at 12:27
  • 1
    The parentheses are not irrelevant here. Assignment has a higher priority than the comma operator, so without them, the sample would fail to compile – divinas Sep 17 '19 at 12:28
  • @divinas This is not assignment, it's initialization. The parentheses are needed because without them this wouldn't compile (a variable name would be expected after each comma). – interjay Sep 17 '19 at 12:28
  • @Mansoor: That's absolutely not the case. – Bathsheba Sep 17 '19 at 12:29
  • @interjay: You're right, that really isn't assignment. But the sample still fails to compile without parentheses: https://godbolt.org/z/VBDZnH – divinas Sep 17 '19 at 12:31
  • 1
    @Mansoor The parentheses are necessary. Otherwise, the `,` is not recognized as operator [Demo](http://coliru.stacked-crooked.com/a/c5e3cdd6520a763d), but as separator for declarations. – Scheff's Cat Sep 17 '19 at 12:32
  • 2
    Missing the point of the question, OP may have thought that the parenthesis would turn the expression into a collection, this is not the case. So yes, they are necessary but do not do what was intended. – Mansoor Sep 17 '19 at 12:38

1 Answers1

5

(1, 2, 3, 4, 5) is an expression of type int with a value of 5. The expression separator operator , evaluates both arguments (sequenced from left to right), but the value of the second argument is the value of the overall expression.

So your code is equivalent to

auto asd = 5;
Bathsheba
  • 231,907
  • 34
  • 361
  • 483