tags:

views:

157

answers:

4

Is there any way I can catch and warn about redundancies at compile time?

Such as

if (abc && abc)

or

if (def || def)

Ok, this isn't actually from an optimisation point of view - I'm thinking more along the lines of a mistake in code - so when the coder intended to write

if (abc && abc)

when actually they meant to write

if (abc && def)

The compiler is going to silently optimise away the mistake, whereas I actually want to know if I can get the compiler to warn me if that has happened, in case it's in there by mistake!

+5  A: 

First, those technically aren't tautologies, they're redundancies. Tautology means it's always true, for example

if (abc || !abc)

And for catching them - you don't have to do anything, any compiler worth it's salt will optimize that away for you. But I sure hope you don't actually have code like that.

Tesserex
If it's a basic type it can be optimized away, but if abc is an object with a boolean or numeric cast operator defined then the compiler shouldn't optimize it since there's no guarantee that the cast will return the same value if called twice.
tloach
That is true, thanks.
Tesserex
My mistake - I've changed the question - thanks!
Tim Gradwell
+2  A: 

Set your compiler to maximum warning level. Check the warnings.

Cătălin Pitiș
I tried that in visual studio - no warning appeared.
Tim Gradwell
Why would you expect a warning? What's wrong with the code?(from the code point of view)
Christian Sciberras
Christopher Barber
+2  A: 

A good compiler will take care of this for you, if you compile with optimization turned on. With gcc, for instance, your first example compiles to (no optimization):

    movl    %esp, %ebp
    subl    $8, %esp
    cmpl    $0, 8(%ebp)
    je      L2
    cmpl    $0, 8(%ebp)   ; checking abc again!
    je      L2
      ...      
L2:

whereas with optimization turned on, the second compare goes away:

    pushl   %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    movl    8(%ebp), %eax
    testl   %eax, %eax
    jne     L4
    leave
    ret
L4:
      ...
I. J. Kennedy
What are you declaring abc to be? The compiler shouldn't optimize out anything other than a basic type.
tloach
+3  A: 

If you're looking for a tool that statically checks for dubious-looking code, you most likely need some form of lint. Industrial-strength lint implementations check for many, many things--I don't know if it will check for the kind of redundancy you gave as an example, but it's worth a try.

I. J. Kennedy
I reckon that's exactly what I'm looking for. Thanks!
Tim Gradwell