Question

In C++, is the following a safe practice:

int a;
int b;

while(stream >> a >> b) { // stream is std::cin or a stringstream
    //do something with a and b
}

Are a and b a guaranteed to be initialized with a value from the stream inside the while loop?

Was it helpful?

Solution

Yes, this is safe in this case [as long as the implementation of the stream and operators follow what the standard says they should do]

Of course, if you have different types than int, say mytype, and have custom made istream& operator >>(istream&, mytype&) defined for your class, it's entirely possible to have a bug in the code that causes some/all of the fields of mytype to be uninitialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top