RE: [avr-gcc-list] Tip: handling volatile operands

From:

Dave Hansen

Subject:

RE: [avr-gcc-list] Tip: handling volatile operands

Date:

Fri, 11 Jan 2008 10:40:44 -0500

> From: address@hidden> > The point I was trying to make (poorly) was that io (and other > variables) that may universally declared volatile, may in fact have > values that need to be used in a "non-volatile" fashion.> > You have same problem with unrollable operations such as:> > if (ioport == 1)> else if (ioport == 2)> else if (ioport == 99)> > So, copy to temporary seems a more general solution - if "non volatile" > access is required.

In cases such as these, a copy to a temporary would be required -- the value of the port could change between tests. If you fail to use a temporary, not only are you generating multiple reads to the port, but you are also opening a window where all the tests could fail when at least one of them should succeed.

Another solution in this particular case would be to replace the if-else cascade with a switch.

switch (ioport) { case 1: ... case 2: ... case 99: ... }

This is (IMHO) a closer abstraction of what you actually want done. Though you have to be clever if you're going to mask bits like the original example. In which case an if-else cascade using a temporary would be better.