6031:在Visual Studio 2019中忽略了返回值(getchar())

6031: return value ignored (getchar()) In visual studio 2019

本文关键字:返回值 getchar Visual Studio 2019 6031      更新时间:2023-10-16

它不会影响我的代码,但在我更新我的Visual Studio之前,我从未见过这样的问题。我不知道这是否连接,但我非常困惑为什么会有问题。

#include <iostream>
#include <string>
#include <array>
using namespace std;
int main() {
    const int SIZE = 3;
    array<string, SIZE> names = { "S","A","W" };
    array<string, SIZE>::iterator it;
    cout << "names: n";
    for (it = names.begin(); it != names.end(); it++)
        cout << *it << endl;

    getchar();
    return 0;
}

当Visual Studio更新时,他们为getchar添加了[[nodiscard]]属性。这告诉编译器在忽略函数的返回值时警告用户。您可以在此处了解更多信息:https://en.cppreference.com/w/cpp/language/attributes/nodiscard

在这种情况下,由于使用 getchar 只是为了防止窗口关闭,因此不需要返回值,因此可以忽略此警告。

我们可以通过显式忽略返回值来使警告静音:

(void)getchar(); //Explicitly ignore return value

在这种情况下,我个人的解决方法是在控制台中暂停,将其加倍,如下所示:

getchar(

(;getchar((;

使用 (void)getchar() 会导致另一个分析警告。

要么使用上述杂注(丑陋(抑制,要么使用

std::ignore=getchar();

我希望他们采用 C# 风格,即

_ = getchar();

有人可能会争辩说,对于通常用于在控制台应用程序末尾接受回车键的函数来说,[[nodiscard]]是矫枉过正的。我希望[[nodiscard]]谨慎使用,只有当您需要对结果采取行动时,例如释放内存或解释错误代码。