Menu

Division by zero warning with specified template

2024-08-26
2024-08-28
  • Jesse Arroyo

    Jesse Arroyo - 2024-08-26

    We have a case where we are getting the following error for templated code. There is a template specification for the 0 case which works for the compiler to avoid the problem, but cppcheck doesn't seem to recognize that

    Toy.C:17:19: warning: Division by zero. [zerodiv]
    return ticket % DIVISOR;

    Any chance this can be improved in the parsing or would this be a caase where we have to hard suppress this? Here is the simplified code that still hits it

    template<unsigned DIVISOR>
    class Foo
    {
        public:
            Foo();
            unsigned remainder(unsigned ticket);
    };
    
    template<unsigned DIVISOR>
    Foo<DIVISOR>::Foo()
    {
    }
    
    template<unsigned DIVISOR>
    unsigned Foo<DIVISOR>::remainder(unsigned ticket)
    {
        return ticket % DIVISOR;
    }
    
    template<>
    unsigned Foo<0>::remainder(unsigned ticket)
    {
        // This is a specialized templatized method of the more general one directly above.  Without
        // this, we get a division by zero compiler error message for the expression "ticket % DIVISOR"
        // when the template parameter DIVISOR is zero.  The compiler uses this version of the method
        // when DIVISOR==0, and the one above when DIVISOR!=0 (i.e., when none of the specialized
        // overrides are an exact match).
        return 0;
    }
    
    unsigned get_remainder(unsigned ticket)
    {
        Foo<0> f;
        return f.remainder(ticket);
    }
    
     
  • CHR

    CHR - 2024-08-26

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/13041
    I guess this is unlikely to get fixed in the short term.

     
  • Jesse Arroyo

    Jesse Arroyo - 2024-08-28

    Thank you

     

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.