Monday, March 26, 2012

#define in C

Simple Define Statements
One of the uses of the #define statement is to define simple constant format is this:
#define SYMBOL value /* comment */
The SYMBOL is any valid C symbol name (by convention, #define names are all uppercase). The value can be a simple number or an expression.
Like variable declarations, a constant declaration needs a comment explains it. This comment helps create a dictionary of constants.
Some examples:
/* Max number of symbols in a procedure */
#define SYMBOL_MAX 500
/* The longest name handled by this system */
#define NAME_LENGTH 50
#define constants are declared like variables. Always put a comment describes the constant after each declaration.
Constant names are all upper-case.

Constant expressions

If the value of a #define statement is a compound expression, you can run problems. The following code looks correct, but it hides a fatal flaw.
/* Length of the object (inches) (partl=10, part2=20) */
#define LENGTH 10 + 20     /* Bad practice */
#define WIDTH 30           /* Width of table (in inches) */
/*..... */
/* Prints out an incorrect width */
printf( "The area i s %d\n" , LENGTH * WIDTH);
Expanding the printf line, you get:
printf( "The area i s %d\n" , LENGTH * WIDTH);
printf( "The area i s %d\n" , 10 + 20 * WIDTH);
printf( "The area i s %d\n" , 10 + 20 * 30);
This another example of how the C preprocessor can hide problems. Clearly LENGTH is 10 + 20, which is 30. So LENGTH is 30, right? Wrong. LENGTH literally 10 + 20 , and:
10 + 20 * 30
is vastly different from:
30 * 30
To avoid problems like this, always surround all #define expressions with parenthesis ()  ). Thus, the statement:
/* Length of the object (inches) (partl=10, part2=20) */
#define LENGTH 10 + 20       /* Bad Practice */
Becomes:
/* Length of the object (inches) (partl=10, part2=20) */
#define LENGTH (10 + 20)       /* Good Practice */
If the value of a constant is anything other than a single number, enclose it in parentheses.

Useful Links:
http://www.oualline.com/style/c06.html 

No comments:

Post a Comment