Menu

format string argument type does not respect C++-style cast

2019-02-07
2019-02-16
  • Paul Cornett

    Paul Cornett - 2019-02-07
    void f(int x)
    {
        printf("%u", (unsigned)x);
        printf("%u", unsigned(x));
    }
    

    cppcheck --enable=warning --language=c++ t.cpp

    elicits

    [t.cpp:4]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'int'

    for line 4 but not for line 3.

     
  • versat

    versat - 2019-02-07

    It really seems like Cppcheck does not handle these functional casts. At least in this case.

    #include <cstdio>
    
    void f(int x)
    {
        printf("%u", (unsigned)x);
        printf("%u", unsigned(x));
    }
    
    $ g++ -Wall -Wextra -fsyntax-only t.cpp && ./cppcheck --enable=all --debug t.cpp
    Checking t.cpp ...
    
    ##file t.cpp
    3: void f ( int x@1 )
    4: {
    5: printf ( "%u" , ( unsigned int ) x@1 ) ;
    6: printf ( "%u" , unsigned int ( x@1 ) ) ;
    7: }
    
    ##Value flow
    Line 5
      "%u" always "%u"
    Line 6
      "%u" always "%u"
    [t.cpp:6]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'int'.
    [t.cpp:3]: (style) The function 'f' is never used.
    (information) Cppcheck cannot find all the include files (use --check-config for details)
    

    Even with a typedef it does not work:

    #include <cstdio>
    typedef unsigned int uint;
    
    void f(int x)
    {
        printf("%u", (unsigned)x);
        printf("%u", uint(x));
    }
    
    $ g++ -Wall -Wextra -fsyntax-only t.cpp && ./cppcheck --enable=all --debug t.cpp
    Checking t.cpp ...
    
    ##file t.cpp
    4: void f ( int x@1 )
    5: {
    6: printf ( "%u" , ( unsigned int ) x@1 ) ;
    7: printf ( "%u" , unsigned int ( x@1 ) ) ;
    8: }
    
    ##Value flow
    Line 6
      "%u" always "%u"
    Line 7
      "%u" always "%u"
    [t.cpp:7]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'int'.
    [t.cpp:4]: (style) The function 'f' is never used.
    (information) Cppcheck cannot find all the include files (use --check-config for details)
    
     
  • versat

    versat - 2019-02-07

    Thank you for the report.
    I created ticket 8969

     
  • Paul Cornett

    Paul Cornett - 2019-02-16

    Might have something to do with unsigned expanding to unsigned int, as casting to int works as expected.

    void f(unsigned x)
    {
        printf("%d", int(x));
    }
    
     

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.