#define is a C preprocessor. There are other ways of making the best usage of #define for writing efficient programs , for the purpose of testing and debugging, for deciding the course of action of the programs
When we first learn about #define, the commonly said example is define some commonly used values like PI, NAME_LEN ,… But there are other uses of #define.
Let me show some aspects of #define
The general syntax of #define
#define identifier(identifier,..., indentifier) token_sequence
1. It is not necessary that all the identifiers used in token sequence is already defined
#define A B+20 #define B 10
As you can see that B was not defined when A is being defined. So the only condition is that we need to define it somewhere.
2. Using gcc, you can define macros and decide the course of your programming. For example, if I wish to perform debugging. I will define __DEBUG__ through gcc.To define macros using gcc, compile using the D option of gcc
gcc -Dmacro[=defn]...]
The following code snippet depicts this
#include <stdio.h>
/*This program shows how to make the use of #define to define the course
*of programming
*/
#define A B+20 /B is not defined here, but will be defined later/
#define B 10
int main()
{
#ifdef __DEBUG__
printf("__DEBUG__ DEFINED\n");
printf("%d\n",A);
#else
printf("__DEBUG__ not defined\n");
printf("%d\n",B);
#endif
return 0;
}
If I compile
$gcc test.c
Output:
__DEBUG__ not defined
10
If I compile
$gcc -D __DEBUG__ test.c
Output:
__DEBUG__ defined 30
Thus we can see how the C Preprocessors also help in deciding the course of action of a program. The above is also called Conditional Compilation