Menu

RFC: Add an option to warn on c-style cast usage

2019-09-12
2019-09-12
  • Sven Strickroth

    Sven Strickroth - 2019-09-12

    g++ supports the flag "old-style-cast" which can be used to issue warnings on c-style cast usage in C++ code (cf. https://stackoverflow.com/a/2593492/3906760). Other compilers, such as MSVC (cf. https://developercommunity.visualstudio.com/idea/550695/add-compile-option-to-warn-on-c-style-cast-usage.html), don't have such an option ATM.

    C-Style casts are often considered bad code practice. The problem is that it is hard to search the source code for C-Style cast. Therefore, C-style cast detection for cppcheck (optional!) would be really helpful to enforce "better" coding conventions and prevent possible hazardous casts.

     

    Last edit: Sven Strickroth 2019-09-12
  • Daniel Marjamäki

    See cstyleCast.

    struct Base {};
    struct Derived : public Base {};
    
    void f(Base *base)
    {
        dostuff((Derived *)base);
    }
    

    Cppcheck output:

    $ ./cppcheck --enable=style 1.cpp 
    Checking 1.cpp ...
    1.cpp:7:13: style: C-style pointer casting [cstyleCast]
        dostuff((Derived *)base);
                ^
    
     
  • Daniel Marjamäki

    If you see some false negatives.. can you please elaborate somewhat..

     
  • Daniel Marjamäki

    struct SCNotification *scn = (struct SCNotification *) lParam;
    

    hmm.. this is a integer to pointer cast . not sure maybe we did not warn about this by intention. I guess you could use reinterpret_cast but does that offer any protection at all compared to a raw C style cast?

        if (TranslateCharsetInfo((DWORD *)(UINT_PTR)iDefaultCodePage, &ci, TCI_SRCCODEPAGE))
    

    I am not sure what are intentions was here neither.

    The warning was added because C++ casts have better protection.

     

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.