Combining C's volatile and const keywords
(#3) Read-only hardware register
Sometimes you will run across a read-only hardware register. In addition to enforcing compile-time checking so that the software doesn't try to overwrite the memory location, you also need to be sure that each and every requested read actually occurs. By declaring your variable IS A (constant) pointer TO A constant and volatile memory location you request all of the appropriate protections, as in:
uint8_t const volatile * const p_latch_reg = (uint8_t *) 0x10000000;As you can see, the declarations of variables that involve both the volatile and const decorators can quickly become complicated to read. However, the technique of combining C's volatile and const keywords can be useful and even important in the above scenarios.
The proper use of volatile and const and the combination of the two keywords is definitely something you should learn along you path to becoming a master embedded software engineer.
Michael Barr is a former lecturer at University of Maryland and Johns Hopkins University and the author of three books and more than sixty-five articles and papers about embedded systems design. In addition to his work designing embedded systems ranging from medical devices to consumer electronics, Mr. Barr has been admitted as a testifying expert witness in numerous U.S. and Canadian court cases covering issues of patent infringement and validity, software quality, theft of copyrighted source code, and satellite TV piracy. Mr. Barr holds BSEE and MSEE degrees. Contact him via e-mail at mbarr@netrino.com or read his blog at http://embeddedgurus.com/barr-code.
Additional reading on volatile:
"Introduction to the Volatile Keyword" Nigel Jones (ESP magazine, 2001)
"Place volatile accurately" Dan Saks, 11/16/2005
More by Michael Barr


Loading comments... Write a comment