Ignoring return values in C

前端 未结 10 1452
轻奢々
轻奢々 2020-12-08 13:39

Lately, I started using lint for static code analysis. One of the warning I get sometimes is regarding this issue. Let\'s say for instance that I\'ve got the following funct

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 13:56

    Usually there are not too many functions the value of which you want to ignore. Splint, for example, allows to add a special comment that would let it know, that a return value of a specific function might be ignored. Unfortunately, this in effect disables all 'ignored returned value' warning related to that particular function.

    Here is an example of Splint-clean program:

    #include 
    
    FILE /*@alt void@*/ *fopen(const char *path, const char *mode);
    
    static int /*@alt void@*/ test(void)
    {
       printf( "test called\n" );
    
       fopen( "test", "a" );
    
       return 0;
    }
    
    int main(void)
    {  
       test();
    
       return 0;
    }
    

    The unpleasant part is that you need to add an additional prototype to a system function with a comment somewhere.

    Btw,by default Splint doesn't complain about the return value of printf and of some other libc functions being unused. However, a stricter mode can be activated.

    LINT allows something similar, but I have never used it. Here is what a documentation says.

    LINT lets you mark functions with optional return values by using a directive similar to the #directives of the C preprocessor.

    #pragma optresult

    can be placed immediately before the definition of a function that returns an optional result. LINT then recognizes that this function returns a result that can be ignored; LINT does not give error messages if the result is ignored.

提交回复
热议问题