Author Topic: A tail of two brackets  (Read 5226 times)

Offline mark

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 3236
    • View Profile
    • uTasker
A tail of two brackets
« on: September 01, 2012, 08:36:19 PM »
Hi All

This one is mainly to remind myself to be more careful...

When porting some code from a project using a routine called __modu(x, y), which was a standard modulo function but not available in the target's library the simple solution was to add a macro:
#define __modu(x, y) (x%y)

The new project was soon up and running and delivered for testing and things looked good apart from one quirky piece of behaviour that was quite hard to reproduce.

After some lengthy testing and debugging the cause of the problem was homed in on and it was noticed that this modu() function/macro was not always working correctly. In particular some code doing
int var = __modu(x + z, y); was not always giving the expected result (sometime it was corect but sometime not).

Soon it became clear that the macro was to blame. Whereas the code was fine when calling a subroutine, the macro was doing:
var = (x + z%y); which is actually not want was intended since y%z has priority.
Correct would have been:
var = ((x + z)%y);

So the macro was modified to
#define __modu(x, y) ((x)%(y))
and everyone, including the software, was happy.

So the moral is to be careful (warning to myself) since typing in a couple of brackets at the beginning can quite easly save a day of unnecessary work later. Probably a beginner's mistake in many people's book but probably even more experienced programmers do get caught out now and again...;-)

Regards

Mark