Can gcc accurately catch useless conditionals?

前端 未结 5 1091
萌比男神i
萌比男神i 2020-12-31 05:05

Please examine the following code:

if (foo->bar == NULL);
   foo->bar = strdup(\"Unknown\");

I spent the last part of three hours hun

相关标签:
5条回答
  • 2020-12-31 05:31
    /* foo.c */
    int main() {
       if (1) ; 
       return 0;
    }
    
    gcc -Wextra -c foo.c
    foo.c: In function ‘main’:
    foo.c:2: warning: empty body in an if-statement
    
    0 讨论(0)
  • 2020-12-31 05:37

    In addition to the above, if you find yourself getting frustrated hunting for a bug using valgrind or a similar execution profiler, you should perhaps consider using a static analysis tool, such as lint. Personally, I use PC-LINT, which catches all sorts of these types of bugs.

    0 讨论(0)
  • 2020-12-31 05:41

    Try -Wextra

    0 讨论(0)
  • 2020-12-31 05:46

    As an alternative to the compiler, I find that running an autoindenter over the code helps find these situations.

    In vim for example:

    gg=G
    
    0 讨论(0)
  • 2020-12-31 05:47

    After digging deep into the gcc manual:

    -Wempty-body
        Warn if an empty body occurs in an `if', `else' or `do while' statement. This warning is also enabled by
    -Wextra.
    

    As some other posters wrote, -Wextra should do it

    Sample code:

    int main(){
    
            if (0);
                    printf("launch missiles");
            return 0;
    }
    
    
    $gcc -Wempty-body foo.c
    warn.c: In function ‘main’:
    warn.c:5: warning: suggest braces around empty body in an ‘if’ statement
    
    0 讨论(0)
提交回复
热议问题