Ganesh Jadhav Ganesh Jadhav - 1 year ago 84
C++ Question

My cpp program is not being asking for input.

i have come across this question and could not get why it is not asking for input.
output of the code is cin0.
please explain it why so.

using namespace std;
int main ()
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;

Answer Source

Let's look at it line by line.

int cin;

This line declare a local variable named cin. From now on, whenever you write cin, the compiler always believe you mean this local variable, not the input stream object std::cin.

cin >> cin;

This line read the local variable and perform bit shifting. When both sides of >> operator are integers, it no longer means input; it means bit shifting now.

But that is not the point.

The point is, local variable cin is uninitialized and it is read. The behaviour is undefined. One undefined behaviour in the program can make the behaviour of the entire program undefined.

Also note that, if we ignore the problem of undefined behaviour, the result of the bit shifting is not assigned to anything and therefore lost.

cout << "cin" << cin;

Local variable cin is once again read without initialization. This is another line of undefined behaviour.

Because of undefined behaviour, it is no longer meaningful to say why it output cin0. But we can reasonably imagine the memory of local variable cin happens to contain zero.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download