Where to Put [[nodiscard]]: A Silent Trap with MSVC!

An example of silent sneaky bug, with MSVC giving a *false* sense of security with [[nodiscard]].

Consider the following C++ code snippet:

static [[nodiscard]] int GetSomething()
{
    return 64;
}

If you invoke this function e.g. inside main() like this:

int main()
{
    GetSomething();
}

this code compiles successfully with MSVC!

Even at warning level 4 (/W4, which I use on almost all my VC++ projects)!

Why am I upset? Because in the above code I did discard the return value of GetSomething(), and even with the [[nodiscard]] attribute applied to the function, and compiling at /W4 (warning level 4), the MSVC C++ compiler did not complain. I did want the compiler to complain! 🙂

Dear MSVC C++ compiler, speak up! Say something like: “Hey, you discarded the return value of GetSomething(), which was marked with the [[nodiscard]] attribute. Please fix your code.”

The interesting thing is that, if you change the position of the [[nodiscard]] attribute, putting it before “static”, you get the expected warning:

// Was: 
//   static [[nodiscard]] int GetSomething()
//
// Now put [[nodiscard]] at the beginning of the line,
// before "static":
//
[[nodiscard]] static int GetSomething()
{
    return 64;
}

Now the C++ compiler complains when trying to compile the above code snippet inside main(), with: “warning C4834: discarding return value of function with [[nodiscard]] attribute”. Great!

The problem is that, a wrong behavior was being silently accepted, even at warning level 4! The MSVC compiler gave me a false sense of security!

I compiled the above code in C++20 mode at /W4 with Visual Studio 2022.

Interestingly, I noted that both Clang and GCC C++ compilers refused to compile the code with [[nodiscard]] in the wrong position, while unfortunately MSVC did silently swallowed that.

For example, Clang emitted the following clear error message:

Clang correctly emits an error when [[nodiscard]] is written in the wrong position.

On Windows, my favorite IDE for C++ (and some C#) programming is Visual Studio, and I use the Microsoft Visual C++ compiler (MSVC) to compile my C++ code. I hope they fix this silent sneaky compiler bug as soon as possible.

Leave a Reply