??? 02/26/11 11:33 Read: times |
#181326 - Rule #2 is a bit broken or at least incompletely formulated Responding to: ???'s previous message |
The const keyword shall be used whenever possible, including: * To declare variables that should not be changed after initialization, * To define call-by-reference function parameters that should not be modified (for example, char const * p_data), * To define fields in structs and unions that cannot be modified (such as in a struct overlay for memory-mapped I/O peripheral registers), and * As a strongly typed alternative to #define for numerical constants. Reasoning: The upside of using const as much as possible is compiler-enforced protection from unintended writes to data that should be read-only. Let's think about this: #define M_PI 3.1415926 ... M_PI = 2; or maybe: enum { MAX_COUNT = 100, }; ... MAX_COUNT = 17; Do you see #define or enum as having problems that requires them to require extra protection from "unintended writes to data that should be read-only"? A compiler would catch both the above situations and scream wildly. But let's view the reverse. You have a const int, but you haven't placed it in the code segment (maybe a bug in a linker configuration file). Now you have a const variable that have an address. And if it happens to be stored in a read/write memory region that a pointer error somewhere in the program can modify your const int, suddenly making your program breaking even worse than it did from just a +/- 1 pointer access. And the important thing: C likes a numeric value as size for an array - not an int variable (even if it happens to be const). So there can't be any universal conversion from #define or enum to const declarations. By the way - you didn't follow rule #7 - use of uint8_t or int8_t to force the size of your constant ;) |
Topic | Author | Date |
Multiple public definitions in code banking | 01/01/70 00:00 | |
single const byte in code | 01/01/70 00:00 | |
The meaning of 'const' in ANSI 'C' | 01/01/70 00:00 | |
Yes | 01/01/70 00:00 | |
Keil C51 isn't a C++ compiler | 01/01/70 00:00 | |
Coding Standard Rules - Netrino | 01/01/70 00:00 | |
Rule #2 is a bit broken or at least incompletely formulated | 01/01/70 00:00 | |
issue with #define usage | 01/01/70 00:00 | |
extern const code declaration | 01/01/70 00:00 | |
Insufficient detail | 01/01/70 00:00 | |
Conceptually wrong | 01/01/70 00:00 | |
Thanks, it's working ! | 01/01/70 00:00 | |
Why? | 01/01/70 00:00 | |
correction | 01/01/70 00:00 | |
Fundamental 'C' programming error! | 01/01/70 00:00 |