cin 作为产生垃圾值的变量名

cin as a variable name producing garbage value

对于以下代码:

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

我预计输出为:

cin : <input>

但输出是:

cin : <junk value>

好的,那是你加入白方势力的机会,停止使用using namespace std;

以下示例适用于 int 输入:

#include <iostream>

int main ()
{
       int cin;
       std::cin >> cin;
       std::cout << "cin: " << cin;
       return 0;
}

为什么?在您的示例中,您的本地名称 int cin 将优先于 std 中的 cin 并导致您的程序在未初始化的情况下使用 int 变量具有 UB。

这是一个很好的建议,但题外话可能是用这样的 failbit 来测试 std::cin::operator >> 的结果

好的,让我们剖析您的代码(假设using namespace std):

#include <iostream>
using namespace std;
int main ()
{
       int cin; // Shadows the declaration of cin coming from the iostream header
       cin >> cin; // A bit shift operation on variable cin without capturing the result
       cout << "cin" << cin; // Output of the non initialized variable cin
       return 0;
}

Kinda proof