Macros Vs Functions
Macros
It contains few lines of code
A macro is preprocessed
A macro is expanded in the code
The program size increases
Execution of macros is faster since code is replaced
No type checking is done for macros
Usually used for small code which appear many times
Functions
It contains several lines of code
A function is compiled
Function code is not inserted in the code
The program size does not increase
Functions execute slower
Strict type checking is done for functions.
Usually used for large code that needs to be executed many times.
Conditional Compilation Directives
These directives allow specific parts of the program to be included or discarded based on certain condition. It causes the preprocessor to conditionally suppress the compilation of portions of source code.
#if
Syntax: #if constant-expression
It checks whether the constant expression is true(non-zero).
#ifdef
Syntax: #ifdef identifier
It checks whether the identifier is currently defined using #define directive.
#ifndef
Syntax: #ifndef identifier
It checks if the identifier is not currently defined.
#else
Syntax: #else
It is used with #if, #ifdef, #ifndef to delimit alternative source text to be compiled if the condition is false. It is optional.
#elif
Syntax: #elif constant-expression
It is used with #if, #ifdef, #ifndef or another #elif to indicate alternative code if the condition is false. It is optional. It must be followed by a condition.
#endif
Syntax : #endif newline
This directive ends the scope of the #if, #ifdef, #ifndef, #else, #elif directive.
Example
: Check if macro NUM has an even value & display appropriate message.
#if (NUM%2==0)
printf( “NUM is even”);
#endif
Check if macro NUM has an even or odd value & display appropriate message.
#if (NUM%2==0)
printf( “NUM is even”);
#else
printf( “NUM is odd”);
#endif
Check if macro NUM has 0, positive or negative value and display appropriate message.
#if (NUM==0)
printf( “\n Number is zero”);
#elif(NUM > 0)
printf( “\n Number is positive”);
#else
printf( “\n Number is negative”);
#endif
If macro NUM is defined, then define macro MAX having value 20
#ifdef NUM
#define MAX 20
#endif
If macro NUM is not defined, then define macro NUM having value 20
#ifndef NUM
#define NUM 20
#endif
If macro NUM is defined, then redefine it with value 75. If it is not defined, define it with value 100.
#ifdef NUM
#undef NUM
#define NUM 75
#else
#define NUM 100
#endif
Predifined macros
LINE
Integer value representing the current line in the source code file
FILE
A string literal containing a C string constant which is the name of the source file being compiled
DATE
A string literal in the form “mmm dd yyyy” containing the date on which the preprocessor is being run
TIME
A string literal in the form “hh:mm:ss” containing the time at which the compilation process began
Comments
Post a Comment
Please give us feedback through comments