g++ How to get warning on ignoring function return value

前端 未结 5 1132
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:52

lint produces some warning like:

foo.c XXX Warning 534: Ignoring return value of function bar()

From the lint manual

5条回答
  •  离开以前
    2020-11-30 05:16

    Thanks to WhirlWind and paxdiablo for the answer and comment. Here is my attempt to put the pieces together into a complete (?) answer.

    -Wunused-result is the relevant gcc option. And it is turned on by default. Quoting from gcc warning options page:

    -Wno-unused-result

    Do not warn if a caller of a function marked with attribute warn_unused_result (see Variable Attributes) does not use its return value. The default is -Wunused-result

    So, the solution is to apply the warn_unused_result attribute on the function.

    Here is a full example. The contents of the file unused_result.c

    int foo() { return 3; }
    
    int bar() __attribute__((warn_unused_result));
    int bar() { return 5; }
    
    int main()
    {
        foo();
        bar();    /* line 9 */
        return 0;
    }
    

    and corresponding compilation result:

    $gcc unused_result.c 
    unused_result.c: In function ‘main’:
    unused_result.c:9: warning: ignoring return value of ‘bar’, declared with attribute warn_unused_result
    

    Note again that it is not necessary to have -Wunused-result since it is default. One may be tempted to explicitly mention it to communicate the intent. Though that is a noble intent, but after analyzing the situation, my choice, however, would be against that. Because, having -Wunused-result in the compile options may generate a false sense of security/satisfaction which is not true unless the all the functions in the code base are qualified with warn_unused_result.

提交回复
热议问题