|
Using the Const Modifier
by
George Martin
Start ı Define
and Qualify ı In Other Words ı Sources
and PDF
Although itıs true that change is inevitable,
quite often in embedded software design you want to specify some things
as constant. Certainly you donıt want any unexpected changes. If you
are writing code in C, you are no doubt using char, int,
long, and float to tell the compiler about your data
size and representation. There is another type modifier (or qualifier)
that Iıll bet you know about and donıt use. My New Yearıs resolution
is to use the const modifier, and then Iıll let the compiler
watch out on my behalf.
The const modifier declares that
the data will not be modified during execution. For example:
int a = 5; // a is an integer type
set to 5
const int b = 10; // b is also
an integer type set to 10 and wonıt change
int const b = 10; // identical
in meaning to line above
Both a and b are variables
and have initial values. But, a can be modified by the program,
whereas b cannot. If you go on to write:
a = a+7; // increment this by 7
b++; // increment this by 1
the compiler will flag the second statement,
which alters the variable b. This example is obvious and probably
too simple to be much help unless there are several designers working
on different modules for the same project. But, I bet you have a listing
that looks something like Listing
1.
I hate questions like, "What do
you think this code does?" So I wonıt ask. FLINFO is a
structure describing and characterizing the flash memory devices,
DevTable[] is an array of all the devices you might find soldered
on the board, and FLinfo[MAX_FLASH_DEV] is a table of all the
devices actually found on the board.
As I search and find flash memory devices,
I copy the data from DevTable into FLINFO and update
the BaseAddr. I donıt want DevTable to change as I run
the program, so itıs qualified and const. And, any compiled
code that would modify any of the DevTable values would be
flagged at compile time. In fact, if your code has RAM and ROM, the
compiler probably will place DevTable in ROM.
If you work on larger projects, no doubt
youıve come across the situation where youıve designed a data structure
and another programmer is needed to view your data, perhaps to write
a report or to log the data. That other programmer or code module
should not be modifying your data. What to do?
NEXT
Circuit Cellar provides up-to-date information for engineers. Visit
www.circuitcellar.com for
more information and additional articles.
For subscription information, call (860) 875-2199, subscribe@circuitcellar.com
or subscribe online.
ıCircuit Cellar, the Magazine for Computer Applications. Posted with
permission. |