-1

r has always the last integer between the parenthesis.

What is the output of the following program?

#include <iostream>
using namespace std;
main() {
    int i = 1, j = 2, k = 3, r;
    r = (i, j, k);
    cout << r <<endl;
}

Possible answers:

A - 1
B - 2
C - 3
D - Compile Error

What I want to know is why does this happen.

jww
  • 90,984
  • 81
  • 374
  • 818
Roger PA
  • 23
  • 1
  • 3
  • 3
    [Comma operator](https://en.wikipedia.org/wiki/Comma_operator) – BoBTFish Mar 07 '16 at 21:04
  • @juanchopanza So then it's not a duplicate, at least not of that question. – David Schwartz Mar 07 '16 at 21:05
  • 3
    The short answer to the question in title: because this is how the `C` language was designed to work (and `C++` inherited this behaviour). – axiac Mar 07 '16 at 21:05
  • Your title shows a declaration `int r = (int, int, int);` (assuming the three `int`s refer to expressions rather than the type name), but the code in your question uses an assignment `r = (i, j, k)`. The answer happens to be the same in both cases, but it's best to be precise and consistent. – Keith Thompson Mar 07 '16 at 21:06
  • Perhaps you should peruse this list of resources for learning C++ http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1 – Rob K Mar 07 '16 at 21:10
  • @BoBTFish I think it's not his code. It looks like a question from somewhere. – HolyBlackCat Mar 07 '16 at 21:18
  • Note to @thiagowfx you should have fixed the indentation as well. – user4581301 Mar 07 '16 at 21:27
  • Possible duplicate of [How does the Comma Operator work](http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) – jww Mar 07 '16 at 21:32

1 Answers1

4

This is the comma operator - see https://en.wikipedia.org/wiki/Comma_operator

Therefore r will be given the value of k in this statement

r = (i, j, k);
Ed Heal
  • 57,599
  • 16
  • 82
  • 120