Preprocessor and macros notes
Preprocessor and macros notes
Ans-A software program that processes the source file before sending it to actual
compilation is called preprocessor. While processing the source file, the preprocessor
replaces header files and macros with defined files and values.
The line which starts with '#'(hash) will be processed by preprocessor before the actual
compilation starts.
Preprocessor in C is not a part of the compilation process but done just before compilation.
•Pre-processor only notice #(hash) started statements.
• #(hash) is called as Pre-processor directive.
• The word after #(hash) is called as Pre-processor command.
eg- #include , #define, #undef etc
1. FILE INCLUSION
This directive is used to include header or source files in the current source file before
compilation. With the help of these directives, one can declare or define source code from other
files in the program.
One commonly used file inclusion directive is ‘#includes<stdio.h>’. It is used to include the
standard I/O library.
To include a user-defined header file use file inclusion directive –‘#include “filename”.
2.MACROS DEFINITION
*Ques-(Define macros definition in-term of variable and in-term of functions with suitable
example).
This identifier, known as the macro name, is defined using the #define preprocessor directive.
Macros provide a convenient way to substitute code values throughout program, improving both
readability and maintainability.
Macros are symbolic representations that the compiler replaces with the actual value or code
before the program is compiled.
Syntax
Example
#include <stdio.h>
#define PI 3.14159 //A macro for the value of PI in-term of variable
int main()
{
double radius = 5.0;
double area = PI * radius * radius;
printf("The area of the circle is: %lf\n", area);
return 0;
}
Types of Macros
a) Macros in term of variable
They are similar to constants and are often used to improve code readability and maintainability
by giving meaningful names to commonly used values.
Example-
#define PI 3.14159
Macros in term of functions mimic the behavior of functions. They accept arguments and can
perform complex operations, offering a convenient way to create reusable code.
Eg-
#include<stdio.h>
#define PRODUCT(n) n*n //A macro in-term of function
void main()
{
int j;
j=64/PRODUCT (4);
printf(“%d”,j);
}
3. CONDITIONAL COMPILATION
WAP to find sum of first n natural number using command line argument