Tuesday, January 27, 2009

A blunder ... can compiler help?

Yesterday, as i was writing another code, i made this simple mistake, illustrated by the following example (example only, don't do this!):

int foo(int i)
{
int j = 2;
if(i > 0)
return i; /* here should be j*/
else
return 0;
}

ok, this is not a good example (it is rubbish), yet clarify my point. It is not simply a typo (which can possibly be another blunder, duh!). I wrote 'return i' instead of 'return j' because i thought it should be 'i'. This is called semantical error. It is not syntactical error, nor grammatical error. It is simply a blunder, and worse, it can't be detected by a compiler.

3 comments:

  1. The compiler won't flag it as an error, but it could be a good candidate for a compiler warning.

    In Java, eclipse will flag this sort of thing as a warning. Specifically, this variable is never read from.

    ReplyDelete
  2. to Andrew:
    yes. i've seen several 'clever' compilers can trace allocated-but-not-referred variable. But that's it. If we already referred the variable, and then we mistyped the variable's name (e.g. involving two or more variables) it would be (silently) chaos :)

    but i haven't checked on Eclipse. Thanks for the info.

    ReplyDelete