c define

c define

We already used this directive to define symbolic constants

The general syntax is:

#define macro_name macro_expression

In the above example The macro_name is any valid C identifier. and it is write generally in capital letters to distinguish it from others variable The macro_expansion can be any text. There should be space necessary between macro name and macro expansion.The C preprocessor replaces all the occurrences of the micro_name with the macro_expansion let us take some examples of #define directive

#define FALSE 0
#define TRUE 1
#define PI 3.14556
#define AGE 18

firstly C preprocessor searches for macro_name in the c program and replaces it with macro_expansion. whenever the macro name TRUE appers in the code, then it is replace by 1 so also these types of constants known as symbolic constants. in the above example also we define constant on macro_name PI so whenever mecro_name PI appears in the code it is replace by 3.14556 and so on we can also define any string constant.

#include<stdio.h>
#define
STR "Real power of c are Macros"
int main()
{
printf(STR);
return 0;
}

function like macros:

The #define directive can also used to define macros with parameters. The general syntax is #define macro_name(par1,par2,par3,…..) macro_expansion

in the above example par1,par2,par3 are the formal parameters and the macro_name is replaced with the macro_expansionand and the formal parameters are replaced by the actual parameters pass in the micro call take the example when we define the macros

#define MUL(x,y) ((x)*(y))
#define SUB(x,y) ((x)-(y))

/* program to understand macros with arguments */
#include<stdio.h>
#define
SUB(x,y) ((x)-(y))
#define PROD(x,y) ((x)*(y))
int main()
{
int a,b,x=6,y=3;
a=PROD(x,y);
b=SUB(x,y);
printf("a=%d and b=%d",a,b);
return 0;
}