Preprocessor Derectives in C
Preprocessor Derectives in C
C
Definition
A preprocessor is a program that
processes our source program before it
is passed to the compiler.
The preprocessor works on the source
code and creates “expanded source
code”.
The preprocessor offers several features
called preprocessor directives.
Each of theses preprocessor directives
begin with a # symbol.
The directives can be placed anywhere
in a program but most often placed at the
beginning of the program,before the
function definition.
Preprocessor directives are executed before
compilation.
The various preprocessor directives
are as follows:
1)Macro Expansion (#define)
II)File Inclusion(#include)
III)Conditional Compilation(#ifdef -#endif)
IV)Miscellaneous Directives
(#undef,#pragma-startup,exit,warn)
Macro Expansion
A “macro” is a fragment of code which
has been given a name.
Wherever the name is used,it is
replaced by the contents of the macro.
There are two kinds of macros which
are as follows:
I)Object-like macros resemble data
objects
II)Function-like macros resemble function
calls.
Object –like Macros
The object-like macro is an identifier
that is replaced by value.
It is widely used to represent numeric
constants.
It is called object-like because it looks
like a data object in code that uses it.
Syntax:
#define identifier replacement-text
Examples
#define x 4 x=identifier 4=replacement-text
void main()
{
int a;
a=x;
}
Example:
Preprocessor Operators
The C preprocessor offers the
following operators to help create
macros −
I)The Macro Continuation (\) Operator
A macro is normally confined to a
single line. The macro continuation
operator (\) is used to continue a
macro that is too long for a single line.
For example −
II)The Stringize (#) Operator
The stringize or number-sign operator
('#'), when used within a macro definition,
converts a macro parameter into a string
constant.
This operator may be used only in a
macro having a specified argument or
parameter list.
For example −
# define say(m) printf(#m)
void main()
{
clrscr(); Output:
say(Hello); Hello
getche();
}
III)The Token Pasting (##) Operator
The token-pasting operator (##) within
a macro definition combines two
arguments.
It permits two separate tokens in the
macro definition to be joined into a
single token.
For example −
When the above code is compiled and executed, it
produces the following result −
Syntax :
#pragma exit <function_name>
exit pragma allow the program to specify function(s) that
should be called just before the program terminates through
_exit.
Function is called after main().