Menu

Proposal of additional check

2015-05-08
2015-05-22
  • Alexander Trufanov

    It looks I don't familiar with CPP standards much and I run into this problem today.

    x = a + b?c:d;
    

    It's a conditional assignment mixed with other operator in one statement.
    x is always c or d. a is always ignored. At least for gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13). No warnings are given during compilation.

    I think there is no check for that in cppcheck. Perhaps someone could add it?

     
  • Alexander Mai

    Alexander Mai - 2015-05-10

    Why do you think a is always ignored?
    In the following example you can see the results depends on a:

    #include <stdio.h>
    int foo(int a, int b, int c, int d) {
       int x = a + b?c:d;
       return x;
    }
    
    int main() {
      printf("%d\n", foo(0,1,3,4));
      printf("%d\n", foo(-1,+1,3,4));
      return 0;
    }
    

    You might check out http://en.cppreference.com/w/cpp/language/operator_precedence which explains the rules of operator evaluation.

     
  • Alexander Trufanov

    Hm, then it wasn't the ignorance of a but I wasn't familiar with order of operator precedence for ?:.
    I tried your code - build it with gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13). And got output:

    3
    4
    

    Then I replaced int x = a + b?c:d; with int x = a + (b?c:d);. And got

    3
    2
    

    So a+b?c:d is processed as (a+b)?c:d which I didn't expect.

    I would wish to get a warning from gcc on that during compilation. It barks on every else without {}.
    How do you think, is it only me or it has sense to add such warning to cppcheck?

     
  • Daniel Marjamäki

    Cppcheck should warn about this. Have you tried using --enable=style? Then maybe something in your code confuses Cppcheck, then we want to fix it.

    $ cat 123.c 
    int f(int a, int b) {
        int ret = a + b ? 123 : 456;
        return ret;
    }
    $ ./cppcheck --enable=style 123.c 
    Checking 123.c...
    [123.c:2]: (style) Clarify calculation precedence for '+' and '?'.
    
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.