bearophile wrote:
Through Reddit I've seen another document that shows common little bugs in 
C/C++ code found by a static analysis tool. The bugs shown seem to be real, 
from real software:
http://www.slideshare.net/Andrey_Karpov/add2011-en

From the slides I have selected seven of the bugs, here translated to D2:


enum uint FLAG1 = 0b001;
void main() {
    int x = 1000;
    int y = 1;
    if (!y & x) {} //#1

    uint flags;
    if (flags && FLAG1) {} //#2

    if (y == 0 || 10 || y) {} //#3

    int i;
    for (i = 0; i < 10; i++)
        for (i = 1; i < 5; i++) {} //#4

    if (x || x) {} //#5

    if (x) y = 1; else y = 1; //#6

    auto z = x * y ? 10 : 20; //#7
}


Notes about the bugs:

- In #1 the programmer meant to write if(!(y & x)). This is often a bug.
I would say that disallowing it would _always_ lead to clearer code. It should always be rewritten as:
if (!y && x)  // wasn't a bug, but was unclear
OR
if (!(y & x)) // was a bug
OR in the one-in-a-million case where the existing code is correct:
if ( (!y) & x ) // wasn't a bug, but even this case is clearer: x MUST be evaluated

Making #7 an error would break a lot of my code, unless it were done in a really complicated way (allowing boolean expressions, but not integral ones other than UnaryExpressions). And that seems quite hard to justify.

But I don't find the other cases convincing. They don't seem any more likely to be bugs than not. For example, a variation of case #3:
if (1 || y) {}
is common and completely legitimate. Disallowing that would be very annoying.

Reply via email to