What a difference a bracket makes

if (tolower(name[i] != com->name[i]))
    return false;

Sometimes it seems to me that programming is a long, slow process of proving to myself how stupid I am. Take the statement above as an example. It is from the console process in my Connected Little Boxes project.

The code is comparing a character in a name typed in with a character in a command name. The command name is always in lower case, but I wanted to convert the incoming character to lower case before the comparison so that my device would ignore the case of incoming commands. In other words, I wanted “print” and “PRINT” to be recognised as the same command.

The code above was supposed to stop matching characters as soon is the incoming name and the command name don’t match. That bit works fine. But it doesn’t recognise that “print” and “PRINT” are the same.

This is because the brackets are in the wrong place. The tolower function (which converts a character code to a lower case value) is being applied to the result of the comparison, not to the character in name[i]. A language like C++ will let you get away with this. C# would have told me that it is silly to try and use a number (the result returned by tolower) in a test. The fix is a simple one, put the brackets in the right place:

if (tolower(name[i]) != com->name[i])
    return false;

Now the character in name[i] is converted to lower case and then compared with the stored name.