Chapter 5: Preprocessor
1 Mark Questions
What is Preprocessor?
→ Preprocessor is a program that processes the source code before compilation.
Write syntax of Macro.
→ #define MACRO_NAME value
Expand #ifdef.
→ If Defined
Write syntax of include directive.
→ #include <filename>
→ #include "filename"
What is Macro with Argument?
→ A macro that accepts parameters like a function is called a macro with arguments.
2 Marks Questions
Role of Preprocessor
→ The preprocessor processes the source code before compilation.
It handles various directives like:
#define (macro substitution)
#include (file inclusion)
#ifdef / #ifndef (conditional compilation)
Nested Macro
→ Defining a macro inside another macro is called Nested Macro.
Example:
#define PI 3.14
#define AREA(r) (PI * r * r)
Conditional Compilation
→ It is the process of compiling certain parts of code depending on conditions
using:
#ifdef
#ifndef
#else
#endif
3 Marks Questions
Program using Macro to find Maximum of 2 Numbers
#include<stdio.h>
#define MAX(a,b) (a>b?a:b)
int main() {
int a=10, b=20;
printf("Maximum = %d", MAX(a,b));
return 0;
}
Program using Macro with Argument
#include<stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a=5;
printf("Square = %d", SQUARE(a));
return 0;
}
File Inclusion Directive
→ It is used to include header files or user-defined files using #include.
Nested Macro Example
#define PI 3.14
#define AREA(r) (PI * r * r)
#ifdef and #ifndef Example
#ifdef PI
printf("PI is defined");
#endif
#ifndef MAX
#define MAX 100
#endif
4 Marks Questions
Program to find Square of Number using Macro
#include<stdio.h>
#define SQUARE(x) (x*x)
int main() {
int n;
printf("Enter number: ");
scanf("%d",&n);
printf("Square = %d", SQUARE(n));
return 0;
}
Conditional Compilation with Example
→ Compile specific code based on condition.
Example:
#include<stdio.h>
#define DEBUG
int main() {
#ifdef DEBUG
printf("Debug mode\n");
#endif
printf("Normal Execution\n");
return 0;
}
Various Preprocessor Directives
Macro Substitution → #define
File Inclusion → #include
Conditional Compilation → #ifdef, #ifndef, #else, #endif
Other Directives → #undef, #pragma
Macro Substitution Directive with Example
→ It replaces defined macro with its value.
Example:
#define PI 3.14
#define AREA(r) (PI * r * r)