简体   繁体   中英

What will happen when we declare cin as int and take input from cin with print cin in cout?

#include <iostream>
using namespace std;
int main() {
    int cin;
    cin >> cin;
    cout << "cin is : " << cin;
}

In this code it gets different output in different complier and can't find proper solution.

There are two things you probably don't understand: scope and initialization .

  1. In the code below the global variable v is hidden by local variable v declared in main . All operations in main are performed on main 's v . The same is true for cin . The cin you declared in main is not the same cin declared in std namespace. So, cin >> cin; has a different meaning. You probably expected the same behaviour as std::cin >> cin; .

     double v; int main() { int v; }
  2. c++ allows uninitialized variables. When you write int cin; memory space is allocated for cin , but nothing is written in (the variable is not automatically initialized). Leaving a variable uninitialized may be on purpose or not. Your compiler may be set to warn on uninitialized variables and/or check at run time. If you compile in debug configuration the variables may be automatically set to zero, depending on compiler, but you should not rely on this as your final build will be in release.

The answer to your question "Garbage value, Error, Segmentation fault, Nothing is printed" is garbage value (is this an interview question?):

  • cin is a local integer variable and
  • cin >> cin is different from std::cin >> cin and different from cin >>= cin .

Your code invokes undefined behavior . (Look up that term, it's an important concept that makes C++ an unreliable programming language.)

In the line int cin , you define a variable and don't initialize it.

The undefined behavior happens as soon as you read from the uninitialized cin variable.

The next undefined behavior happens depending on the value of cin . The shift-right operator is an arithmetic operation. If its right-hand side is not between 0 and the bit size of the left operand, the behavior is undefined .

you cannot declare keywords name for variable-name. cin and cout are keywords in c++.Please use different name for variable-name which used in your c++ program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM