Richard Harter’s World
Site map
February 2010
Comp. Sci.
Guest
email

Symbolic constants in register references

In the comp.lang.c newsgroup one of the posters advanced an argument that there is no risk in using naked constants for control registers if there only a single reference, arguing that it is rare for register bit assignments to change. Peter Seebach responded as follows:

There is a very large risk, which is that someone looking at the code will have to go look up a spec sheet to figure out what you’re doing.

There is a HUGE advantage to:

   frob_bits(reg, WIDGET_ENABLE | WIDGET_POWER_ON);

over

   frob_bits(reg, 0x9);

Sure, if you review this, you might have to verify that the settings are right. BUT!

When you review it, you look at the definitions, compare them to the manual, and then you are DONE looking at the register definitions in the manual. Even if any given bit value is used only once, the set of possible bit values may be referred to several times, and only having to compare code to the manual once is a big win.

In short, even if there is exactly one use of WIDGET_ENABLE, it is preferable for it to be a symbolic constant, defined right next to all the other symbolic constants for that register, ideally with lucid comments and a citation to the correct page of the manual.

Naked constants make sense when the constant’s value is intrinsic to the code. They are not appropriate when the constant’s value is determined externally, even if that value is extremely unlikely to change.


This page was last updated February 1, 2010.

Richard Harter’s World
Site map
February 2010
Comp. Sci.
Guest
email