What's wrong with cin >> num1, num2?

后端 未结 3 2001
予麋鹿
予麋鹿 2021-01-26 05:42
#include 
using namespace std;

int main() {
  char choice;
  int solution, num1, num2;

  cout << \"Menu\";
  cout << \"\\n========\";
  cou         


        
3条回答
  •  渐次进展
    2021-01-26 06:25

    int solution, num1, num2;
    

    This leaves all variables uninitialised. Trying to read from them without a previous assignment is undefined behaviour.

    cin >> num1, num2;
    

    The supposed intention of this line is to read into both variables. What happens really is an application of the comma operator, with operands cin >> num1 on the left side and num2 on the right side.

    The left side is evaluated and a value is written to num1; the second operand has no effect and leaves num2 in its uninitialised status.

    It's as if you had written cin >> num1;.

    solution = num1 + num2;
    

    The aforementioned undefined behaviour happens, rendering your entire program invalid.

    You can fix the problem as follows:

    cin >> num1;
    cin >> num2;
    

提交回复
热议问题