Basic Preprocessors in C Programming | Programming and Data Structures - Computer Science Engineering (CSE) PDF Download

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −

DirectiveDescription
#defineSubstitutes a preprocessor macro.
#includeInserts a particular header from another file.
#undefUndefines a preprocessor macro.
#ifdefReturns true if this macro is defined.
#ifndefReturns true if this macro is not defined.
#ifTests if a compile time condition is true.
#elseThe alternative for #if.
#elif#else and #if in one statement.
#endifEnds preprocessor conditional.
#errorPrints error message on stderr.
#pragmaIssues special commands to the compiler, using a standardized method.


Preprocessors Examples

Analyze the following examples to understand various directives.

#define MAX_ARRAY_LENGTH 20

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.

#include <stdio.h>
#include "myheader.h"

These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.

#undef  FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG
/* Your debugging statements here */
#endif

It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.

Predefined Macros

ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified.
 

MacroDescription
__DATE__The current date as a character literal in "MMM DD YYYY" format.
__TIME__The current time as a character literal in "HH:MM:SS" format.
__FILE__This contains the current filename as a string literal.
__LINE__This contains the current line number as a decimal constant.
__STDC__Defined as 1 when the compiler complies with the ANSI standard.


Let's try the following example −

#include <stdio.h>

main() {

printf("File :%s
", __FILE__ );
printf("Date :%s
", __DATE__ );
printf("Time :%s
", __TIME__ );
printf("Line :%d
", __LINE__ );
printf("ANSI :%d
", __STDC__ );

}

When the above code in a file test.c is compiled and executed, it produces the following result −

File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

Preprocessor Operators

The C preprocessor offers the following operators to help create macros −

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 −

#define  message_for(a, b)  
printf(#a " and " #b ": We love you!
")

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 −

#include <stdio.h>

#define message_for(a, b)
printf(#a " and " #b ": We love you!
")

int main(void) {
message_for(Carole, Debra);
return 0;
}

When the above code is compiled and executed, it produces the following result −

Carole and Debra: We love you!

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 −

#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}

When the above code is compiled and executed, it produces the following result −

token34 = 40

It happened so because this example results in the following actual output from the preprocessor −

printf ("token34 = %d", token34);

This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting.

The Defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows −

#include <stdio.h>

#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif

int main(void) {
printf("Here is the message: %s
", MESSAGE);
return 0;
}

When the above code is compiled and executed, it produces the following result −

Here is the message: You wish!

Parameterized Macros

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows −

int square(int x) {
return x * x;
}

We can rewrite above the code using a macro as follows −

#define square(x) ((x) * (x))

Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example −

#include <stdio.h>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void) {
printf("Max between 20 and 10 is %d
", MAX(10, 20));
return 0;
}

When the above code is compiled and executed, it produces the following result −

Max between 20 and 10 is 20
The document Basic Preprocessors in C Programming | Programming and Data Structures - Computer Science Engineering (CSE) is a part of the Computer Science Engineering (CSE) Course Programming and Data Structures.
All you need of Computer Science Engineering (CSE) at this link: Computer Science Engineering (CSE)
119 docs|30 tests

Top Courses for Computer Science Engineering (CSE)

FAQs on Basic Preprocessors in C Programming - Programming and Data Structures - Computer Science Engineering (CSE)

1. What is a preprocessor in C programming?
Ans. A preprocessor in C programming is a tool that processes the source code before it is compiled. It performs various tasks such as macro substitution, file inclusion, and conditional compilation. The preprocessor directives start with a hash symbol (#) and are executed before the actual compilation of the code.
2. What are the benefits of using preprocessors in C programming?
Ans. Preprocessors in C programming provide several benefits. They allow code reusability by using macros, which are predefined code snippets. Preprocessors also enable conditional compilation, allowing different parts of the code to be compiled based on specific conditions. They facilitate file inclusion, allowing the inclusion of header files that contain function prototypes and definitions. Additionally, preprocessors enhance code readability by abstracting complex code into simpler macros.
3. How do I use macros in C programming with preprocessors?
Ans. Macros in C programming are defined using the #define directive. They provide a way to define a code snippet that can be used multiple times in the program. Macros can have parameters and are expanded by the preprocessor during compilation. To use a macro, you simply need to invoke it in your code by specifying its name and providing any required arguments.
4. Can I include multiple header files in a C program using preprocessors?
Ans. Yes, you can include multiple header files in a C program using preprocessors. The #include directive is used to include header files in the program. You can include multiple header files by using multiple #include directives, each specifying a different header file. This allows you to access functions, constants, and structures defined in those header files within your program.
5. How can I conditionally compile parts of my C program using preprocessors?
Ans. Conditional compilation in C programming is achieved using preprocessor directives such as #ifdef, #ifndef, #if, #else, and #endif. By using these directives, you can define certain parts of code to be compiled only if specific conditions are met. For example, you can include or exclude debugging statements based on whether a DEBUG flag is defined or not. This allows you to have different versions of your program with varying features or behaviors based on compile-time conditions.
119 docs|30 tests
Download as PDF
Explore Courses for Computer Science Engineering (CSE) exam

Top Courses for Computer Science Engineering (CSE)

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

study material

,

video lectures

,

Summary

,

Free

,

ppt

,

shortcuts and tricks

,

Viva Questions

,

Extra Questions

,

Exam

,

Previous Year Questions with Solutions

,

Basic Preprocessors in C Programming | Programming and Data Structures - Computer Science Engineering (CSE)

,

MCQs

,

Semester Notes

,

practice quizzes

,

Important questions

,

past year papers

,

Basic Preprocessors in C Programming | Programming and Data Structures - Computer Science Engineering (CSE)

,

Sample Paper

,

mock tests for examination

,

Objective type Questions

,

pdf

,

Basic Preprocessors in C Programming | Programming and Data Structures - Computer Science Engineering (CSE)

;