Search code examples
c++coding-stylecode-generationiostream

I'm curious about c++ istream assignment


I have some question about this code :

#include <iostream>
using namespace std;

int main() {
    int i;
    int w[10];

    cin >> i >> w[i];
    cout << i << ' ' << w[i];
    return 0;
}

standard inputs are :

3 10

In my PC(Win10 64bit, gcc version : g++ 6.3.0), it occurs segmentation fault. enter image description here

But other environment(like https://ideone.com/i5Vd7o) can execute it.

It works fine when I edit this section :

cin >> i >> w[i];

to this :

cin >> i;
cin >> w[i];

So 2 small questions come out:

  1. What is the standard of istream assignment? Should the assigned variable be read from current line or next line?
  2. Which one is 'nice code' for readers if compiler supports both of them?

Solution

  • You’re running into undefined behaviour before C++17. When executing

    int i;
    int w[10];
    
    cin >> i >> w[i];
    

    i has not been initialised and reading its value is undefined. The line that reads i and w[i] attempts to read i to find out the location of w[i] before a value is put into i from the input stream due to C++’s order of evaluation.

    Your second statement works, because here i is read from the standard input, and is subsequently used to compute w[i] in a separate statement.

    In C++17, this behaviour changed, and std::cin >> i >> w[i] is now well-defined, because the left-hand side of each >> is computed before the right-hand side, including its computation. This means that in a chain of left-associative >> invocations, std::cin >> i is fully executed beforew[i]` is computed.