MPLABX is going to be a great tool in a few years. While fighting with it today I ran into some problems that reminded me of this.
We can write code like this
After the text preprocessor does it magic the file sent to the compiler will contain something like this. I commented out PEOPLE_MAX because it does not survive past the preprocessor.
I suggest a better version is this.
If you are thinking the 2nd version will use more memory you would be mistaken. In the first version the compiler creates a constant variable too. But it is on that is hidden from us.
In the 2nd version the constant PeopleMax is know to the compiler, debugger, and printf debug statments (for people not using debuggers).
Most compilers will not let you easily change the value of a constant.
#define is better used for condition compilation.
The preprocessor is a great tool but we are better off not using it for constants.
We can write code like this
Code:
#define PEOPLE_MAX 666
...
int people[PEOPLE_MAX];
...
while (i<[PEOPLE_MAX])
....
Code:
//#define PEOPLE_MAX 666
...
int people[666];
...
while (i<666)
....
Code:
const unsigned int PeopleMax = 666;
...
int people[PeopleMax];
...
while (i < PeopleMax)
....
If you are thinking the 2nd version will use more memory you would be mistaken. In the first version the compiler creates a constant variable too. But it is on that is hidden from us.
In the 2nd version the constant PeopleMax is know to the compiler, debugger, and printf debug statments (for people not using debuggers).
Most compilers will not let you easily change the value of a constant.
Code:
PeopleMax=32;
generates the error
E:\Users\3v0...\main.c:50:Error [1102] cannot assign to 'const' modified object
#define is better used for condition compilation.
Code:
#define DEBUG_ME
#ifdef DEBUG_ME
printf("the value of PeopleMax: %d", PeopleMax);
#endif
// which will output
the value of PeopleMax: 666
The preprocessor is a great tool but we are better off not using it for constants.