Chara
Chara

Reputation: 1075

Storing number larger than INT_MAX in an int

Can someone explain this C++ behaviour to me?

for (int i=0;i<3;++i){
    int x;
    std::cin >> x;
    std::cout << x << std::endl;
}

If I input a number larger than INT_MAX (like 124124124124124) only ONCE, this outputs:

2147483647
2147483647
2147483647 

My best guess is that it recognizes my input is a number, but it slices because x can only fit up to 2147483647. What I don't understand is why after inputting that big number only ONCE, the input "overflows" to the other inputs, and prints 2147483647 three times, then ends the program.

Upvotes: 0

Views: 873

Answers (1)

Chad
Chad

Reputation: 19032

The stream extraction operator >> notes that you can't stream in that large number and sets the fail bit, and does not modify the value of x.

Subsequent reading from that input stream (cin in this case) fail immediately, and thus the value of x remains unchanged (and in this case, undefined).

Upvotes: 5

Related Questions