Can I detect (and warn on) redundancies at compile time?
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 opt开发者_StackOverflow社区imise 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!
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.
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.
Set your compiler to maximum warning level. Check the warnings.
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:
...
精彩评论