Preprocessor Syntax
#directive_name arguments
Example : #include <stdio.h>
File Inclusion Directive
The file inclusion directive is #include.
The #include directive instructs compiler to include/insert contents of the specified file at that position.
Syntax:
#include <filename>
OR
#include "filename“
First format searches for the file in standard directories only. Second format first searches for the file in the current directory. If not found search continues in the standard directories. An included file can include other files.
Example
#include <stdio.h>
#include<string.h>
/*group.h*/
#include<stdio.h>
#include<math.h>
#include “myfile.c”
/*mainprog.c*/ #include “group.h” main()
{
----
----
}
Macro Substitution Directive
#define is a macro substitution directive
It defines symbol which represents a value
Macro name is substituted by code of the macro.
Syntax
#define macro_name value
It defines symbolic constant which occur frequently in a program
Examples
#define PI 3.142
#define TRUE 1
#define AND &&
#define LESSTHAN <
#define GREET printf(“Hello”);
#define MESSAGE “Welcome to C”
#define INRANGE (a>=60&& a<70)
Argumented Macros
Just like a function, a macro can be defined with arguments. Such macro is called a function macro because it looks like a function.
Example:
#define HALFOF(x) x/2
#define SQR(x) x*x
#define MAX(x,y) ( (x) > (y) ? (x) : (y))
Example:
result=HALFOF(10); //replaced by result=10/2; ans=SQR(a); //replaced by ans=a*a; It is advisable to enclose the arguments in ( ), if not it may yield wrong results.
Example:
result = HALFOF(10+6);
This will be evaluated as result = (10+6/2); and will give incorrect results.
The correct way to define macro would be:
#define HALFOF (x) ((x)/2)
Now, result=((10+6)/2); which will give the correct result.
Nested Macros
A macro can be contained within another macro. This is called as nesting of macros.
Example:
#define SQR(x) (x)*(x)
#define CUBE(x) SQR(x)*(x)
#define CUBE(x) (x)*(x)*(x)
In this example, macro SQR is called in macro named CUBE.
#define MAX(a,b) ((a)>(b) ? (a) : (b))
#define MAXTHREE(a,b,c) MAX(MAX(a,b),c)
Comments
Post a Comment
Please give us feedback through comments