Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      C attribute: nodiscard(since C23)

      From cppreference.com
      <c‎ |language‎ |attributes
       
       
       
       
      Attributes
      nodiscard
      (C23)
      (C23)(C23)(deprecated)
       

      If a function declarednodiscard or a function returning a struct/union/enum declarednodiscard by value is called from adiscarded-value expression other than a cast tovoid, the compiler is encouraged to issue a warning.

      Contents

      [edit]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

      [edit]Explanation

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

      If, from adiscarded-value expression other than a cast tovoid,

      • a function declarednodiscard is called, or
      • a function returning a struct/union/enum declarednodiscard is called,

      the compiler is encouraged to issue a warning.

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

      [edit]Example

      Run this code
      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(){staticstruct 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 valueint z= strategic_value(0,0);// OK: return value is not discardedreturn z;}

      Possible output:

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

      [edit]See also

      C++ documentation fornodiscard
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/language/attributes/nodiscard&oldid=124537"

      [8]ページ先頭

      ©2009-2026 Movatter.jp