| ??? 09/12/02 08:40 Read: times |
#29055 - RE: Define Vs Constant |
"Is there any advantage of using a #define over a Constant?"
What exactly do you mean by a "Constant" in this context; eg, are you thinking of something like: #define BAUD 9600 : set_uart_speed( BAUD );as opposed to just:: set_uart_speed( 9600 );In this case, the advantage lies in giving a meaningful name to the constant (as opposed to just a meaningless "Magic Number"). Also, if the same constant is used in many places, it is much easier to maintains & update the code - you just change one #define, instead of having to search out all the occurrences of the "Magic Numbers" In this case, it makes absolutely no difference at all to the generated code - they both end up as literal constant values as far as the Compiler is concerned. In this case, there is no benefit of type checking. enum constants are very simialt to #defines, but do add the possibility for type-checking & recognition by a debugger (but Keil at least doesn't take advantage of this) The const qualifier can be added to a variable definition to specify that it should never be modified; the compiler should warn if it spots an attempt to modify such a variable, but the effect of const is otherwise implementation-defined (see K&R). const is commonly used by embedded compilers to indicate fixed values to go into ROM; eg, const char msg[] = "ACME Wotsit v2.03";Obviously this does use up code space, but could help by removing the need to copy the data into RAM where it could be modified. |
| Topic | Author | Date |
| Define Vs Constant | 01/01/70 00:00 | |
| RE: Define Vs Constant | 01/01/70 00:00 | |
| RE: Define Vs Constant | 01/01/70 00:00 | |
| RE: Define Vs Constant (Andy) | 01/01/70 00:00 | |
| RE: Define Vs Constant Luca | 01/01/70 00:00 | |
| RE: Define Vs Constant (Andy) | 01/01/70 00:00 | |
| RE: Define Vs Constant (Luca | 01/01/70 00:00 | |
| RE: Const in code | 01/01/70 00:00 | |
| RE: Const in code, Andy | 01/01/70 00:00 | |
| RE: Const in code, Andy | 01/01/70 00:00 | |
| RE: Const in data, Luca | 01/01/70 00:00 | |
RE: Const in code, Luca | 01/01/70 00:00 |



