Search code examples
c++operator-precedencecomma-operator

Why does it receive only 1 integer?


Why does this receive only one integer?
Here is the code:

#include <iostream>

int main () {
    int num1,num2,num3;
    std::cin>>num1,num2,num3;

    return 0;
}

Solution

  • According to the Operator Precedence, comma operator has lower precedence than operator>>, so std::cin>>num1,num2,num3; is same as (std::cin>>num1), num2, num3;; the following num2, num3 does nothing in fact. (More precisely, std::cin>>num1 is evaluated firstly and its result is discarded; then num2 is evaluated, num3 is evaluated at last and its value is the result of the whole comma expression.)

    What you want should be std::cin >> num1 >> num2 >> num3;.