Menu

False division by zero in ternary operator

2024-01-29
2024-01-29
  • Martin Poupě

    Martin Poupě - 2024-01-29

    Have code:

    void f()
    {
     unsigned x,y,s = 0;
            for(x = 0; x < 256;x++)
            {
                for(y = 0; y < 256; y++)
                {
                    unsigned z = (y <= x) ? 255 : (x * 255) / y;
                    s += z;
                }
            }
            printf("%u\n",s);
    }
    

    Both CPPCheck 2.13 and online demo report division by zero:

    error: Division by zero. [zerodiv]
    unsigned z = (y <= x) ? 255 : (x * 255) / y;
    Assignment 'y=0', assigned value is 0
                for(y = 0; y < 256; y++)
    

    But the code will never divide by zero because of that condition (y <= x)

     
  • CHR

    CHR - 2024-01-29

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12385

     

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.