Compiler Warning (level 4, off) C5240

'attribute-string': attribute is ignored in this syntactic position

Remarks

Warning C5240 occurs when a [[nodiscard]] or [[maybe_unused]] attribute is found in the wrong syntactic position. For example, the [[nodiscard]] attribute in this syntactic position applies to the decl-specifier-seq, not to the function f:

static [[nodiscard]] int f() { return 1; }

Before Visual Studio 2019 version 16.10, the compiler would silently ignore uses of a [[nodiscard]] or [[maybe_unused]] attribute in a syntactic position that didn't apply to the function or object being declared. In Visual Studio 2019 version 16.10 and later, the compiler emits off-by-default level 4 warning C5240 instead. For more information on how to enable this warning, see Compiler warnings that are off by default.

Example

The following example shows how warning 5240 can occur:

// c5240.cpp
// Compile using: cl /EHsc /W4 /std:c++17 /permissive- /c c5240.cpp
#pragma warning( default: 5240 )
static [[nodiscard]] int f() { return 1; }  // C5240

To fix this issue, move the attribute to the correct syntactic position:

// c5240_fixed.cpp
// Compile using: cl /EHsc /W4 /std:c++17 /permissive- /c c5240_fixed.cpp
#pragma warning( default: 5240 )
[[nodiscard]] static int f() { return 1; }  // OK

See also

Attributes in C++