Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It does not affect my code, but I have never seen such issue until I updated my visual studio. I don't know if thats connected, but I am very confused why is there an issue.

#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;
}
like image 263
Gleb Avatar asked Sep 04 '25 17:09

Gleb


1 Answers

When visual studio was updated, they added a [[nodiscard]] attribute to getchar. This tells the compiler to warn the user whenever the return value of a function is ignored. You can find out more here: https://en.cppreference.com/w/cpp/language/attributes/nodiscard

In this case, because you're using getchar just to prevent the window from closing, you don't need the return value, so you can ignore this warning.

We can silence the warning by explicitly ignoring the return value:

(void)getchar(); //Explicitly ignore return value
like image 84
Alecto Irene Perez Avatar answered Sep 07 '25 06:09

Alecto Irene Perez