From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/c/language%2Fattributes%2Fnodiscard.html | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 devdocs/c/language%2Fattributes%2Fnodiscard.html (limited to 'devdocs/c/language%2Fattributes%2Fnodiscard.html') diff --git a/devdocs/c/language%2Fattributes%2Fnodiscard.html b/devdocs/c/language%2Fattributes%2Fnodiscard.html new file mode 100644 index 00000000..35c94f7d --- /dev/null +++ b/devdocs/c/language%2Fattributes%2Fnodiscard.html @@ -0,0 +1,42 @@ +

C attribute: nodiscard (since C23) +

If a function declared nodiscard or a function returning a struct/union/enum declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.

+

Syntax

+ + +
[[ nodiscard ]]
[[ __nodiscard__ ]]
(1)
[[ nodiscard ( string-literal ) ]]
[[ __nodiscard__ ( string-literal ) ]]
(2)
+ +
string-literal - text that could be used to explain the rationale for why the result should not be discarded

Explanation

Appears in a function declaration, enumeration declaration, or struct/union declaration.

+

If, from a discarded-value expression other than a cast to void,

+

the compiler is encouraged to issue a warning.

+

The string-literal, if specified, is usually included in the warnings.

+

Example

struct [[nodiscard]] error_info { int status; /*...*/ };
+struct error_info enable_missile_safety_mode() { /*...*/ return (struct error_info){0}; }
+void launch_missiles() { /*...*/ }
+void test_missiles() {
+   enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
+   launch_missiles();
+}
+struct error_info* foo() { static struct error_info e; /*...*/ return &e; }
+void f1() {
+    foo(); // nodiscard type itself is not returned, no warning
+}
+// nodiscard( string-literal ):
+[[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; }
+ 
+int main()
+{
+    strategic_value(4,2); // compiler may warn on discarding a nodiscard value
+    int z = strategic_value(0,0); // OK: return value is not discarded
+    return z;
+}

Possible output:

+
game.cpp:5:4: warning: ignoring return value of function declared with 'nodiscard' attribute
+game.cpp:17:5: warning: ignoring return value of function declared with 'nodiscard' attribute: PURE FUN

See also

+
C++ documentation for nodiscard
+

+ © cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
+ https://en.cppreference.com/w/c/language/attributes/nodiscard +

+
-- cgit v1.2.3