[英]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.在这段代码中,它在不同的编译器中得到不同的 output 并且找不到合适的解决方案。
There are two things you probably don't understand: scope and initialization .有两件事你可能不明白: scope和初始化。
In the code below the global variable v
is hidden by local variable v
declared in main
.在下面的代码中,全局变量
v
被main
中声明的局部变量v
隐藏。 All operations in main
are performed on main
's v
. main
main
v
上执行。 The same is true for cin
. cin
也是如此。 The cin
you declared in main
is not the same cin
declared in std
namespace.您在
main
中声明的cin
与在std
命名空间中声明的cin
不同。 So, cin >> cin;
所以,
cin >> cin;
has a different meaning.有不同的含义。 You probably expected the same behaviour as
std::cin >> cin;
您可能期望与
std::cin >> cin;
相同的行为。 . .
double v; int main() { int v; }
int cin;
int cin;
memory space is allocated for cin
, but nothing is written in (the variable is not automatically initialized).cin
分配了 memory 空间,但没有写入任何内容(变量不会自动初始化)。 Leaving a variable uninitialized may be on purpose or not. 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
是一个本地 integer 变量和cin >> cin
is different from std::cin >> cin
and different from cin >>= cin
. cin >> cin
与std::cin >> cin
和cin >>= cin
不同。 Your code invokes undefined behavior .您的代码调用未定义的行为。 (Look up that term, it's an important concept that makes C++ an unreliable programming language.)
(查看这个术语,这是一个重要的概念,它使 C++ 成为不可靠的编程语言。)
In the line int cin
, you define a variable and don't initialize it.在
int cin
行中,您定义了一个变量并且不对其进行初始化。
The undefined behavior happens as soon as you read from the uninitialized cin
variable.一旦您从未初始化的
cin
变量中读取,未定义的行为就会发生。
The next undefined behavior happens depending on the value of cin
.下一个未定义的行为取决于
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 .
如果其右侧不在 0 和左侧操作数的位大小之间, 则行为未定义。
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.
cin 和 cout 是 c++ 中的关键字。请为您的 c++ 程序中使用的变量名使用不同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.