SlideShare a Scribd company logo
Submitted by
K.Lalithambiga.,Msc(cs),
N.S.College of Arts & Science.
 Introduction
 Macro Substitution
 File Inclusion
 Compiler Control Directives
 ANSI Additions
 The C preprocessor provides several tools that are
unavailable in other high-level languages.
 The programmer can use these tools to make his
program easy to read, easy to modify, portable and
more efficient.
 The C Preprocessor is not a part of the compiler, but
is a separate step in the compilation process.
 The preprocessor is a program that process the code before it
basses through the computer preprocessor directivities are
placed in the source program before the main line.
 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.
 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 −
Directive Description
#define Substitutes a preprocessor macro.
#include Inserts a particular header from another file.
#undef Undefines a preprocessor macro.
#ifdef Returns true if this macro is defined.
#ifndef Returns true if this macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative for #if.
#elif #else and #if in one statement.
#endif Ends preprocessor conditional.
#error Prints error message on stderr.
#pragma Issues special commands to the compiler, using a standardized
method.
 These directivities can be divided into three
categories:
 Macro substitution is a process where an identifier in a
program is replaced by a predefined string composed of one
or more identifiers.
 It accomplishes this task under the direction of ‘#define’
statement. The general form is
 The definition is not terminated by a semicolon. The string
may be any text, while the identifier must be a valid C name.
 There are different forms of macro substitution. The most
common forms are:
Syntax: # define identifier string
 There are different forms of macro substitutions.
The most common forms are
1. Simple macro substitution.
2. Argumented macro substitution.
3. Nested macro substitution.
 Simple string replacement is commonly used to define
constants.
Example :
 We have written all macros(identifiers) in capitals. It is a
conversion to write all macros in capitals to identify them as
symbolic constants.
 It will replace all occurrences of ‘M’ with ‘5’, starting from
the line of identifier to the end of the program.
Example :
# define COUNT 100
# define CAPITAL “DELHI”
# define M 5
Total = M * value ;
Printf(“M = %dn”, M);
 These two lines would be changed during pre-processing as
follows.
Example:
 We can use a macro to define almost anything
Example:
 To build a statement as follows TEST AND PRINT
 The preprocessor would translate this line to
If(x<y) printf(“very good”);
#define TEST if(x<y)
#define AND
#define PRINT printf(“very good”);
Total = 5 * value ;
Printf (“M=%dn” , 5);
 The preprocessor permits to define more useful form of define
replacements. It takes the form
Syntax:
 There is no space between the macro identifier and the left
parentheses. The identifiers f1,f2,…..fn are the formal macro
arguments that are analogous to the formal arguments in a
function definition.
 A macro with arguments is known as a macro call.
 When a macro is called, the preprocessor substitutes the string
replacing the formal parameters with the actual parameters.
# define Identifier(f1,f2,…fn) string
 A simple example of a macro with argument is
 If the following statement appears in the program
 Then the preprocessor would expand this statement as
# define CUBE(X) (x*x*x)
Volume = CUBE(side);
Volume = side * side * side;
 Nesting Of Macros use one macro in the definition of another
macro. The Macro definitions may be nested.
 Consider the following macro definitions.
 The preprocessor expands each #define macro until no more
macros appear in the test. For example the last definition is
first expands into
# define SQUARE(x) (x*x)
# define CUBE(x) (SQUARE(x)*x)
# define SIXTH(x) (CUBE(x)*CUBE(x))
(SQUARE(x)*x) * (SQUARE(x) * x)
 Since ‘SQUARE(x)’ is still a macro, it is further
expanded into
( ( x * x ) * x ) * ( (x*x)*x)
which is finally evaluated as x6.
 Macro calls can be nested in much the same fashion
as function calls.
Example : #define HALF ( (x)/2.0 )
#define Y HALF( HALF(x) )
 A defined macro can be undefined using statement
Syntax:
 This is useful to restrict the definition only to a
particular part of the program.
# undef identifier
 File Inclusion is an external file containing functions or macro
definitions can be included as a part of a program.
 This is achieved by a preprocessor directive.
Syntax:
 The ‘file name’ is the name of the file containing the required
definitions or functions.
 At this point, the preprocessor inserts the entire contents of the
file name into the source code of the program.
 When the file name is included within the (“ ”) ,then the search
for the file is made first in the current directory and then in the
standard directories.
#include “file name”
 Alternatively this directive takes the form
 Without (“ ”) in this case this file can include other files.
However a file can’t include itself.
 We can make use of a definition or function contained in
anyone of these files by including them in the program as
shown below.
#include<stdio.h>
#include“shiva.c”
#define M 5
main( )
{
……………
……………
}
#include <file name>
 Compiler Control Directives is developing large
programs, the ‘C’ pre-processor offers a feature
known as conditional compilation.
 It can be used to ‘switch’ on or off a particular line
or a group of lines in a program.
 These compiler control directives are used in different situations.
They are:
Situation 1:
 This situation refers to the conditional definition of a macro. We
want to ensure that the macro TEST is always defined, irrespective
of whether it has been defined in the header file or not. This can be
achieved as follows:
 DEFINE.H is the header that is supposed to contain the definition
of TEST macro.
 The directive #ifndef TEST searches the definition of TEST in the
header file and if it is not defined, then all the lines between
the #ifndef and the corresponding #endif directive are executed in
the program.
#include ”DEFINE.H”
#ifndef TEST
#define TEST 1
#endif
Situation 2:
 The main concern here is to make the program portable. This
can be achieved as shown below:
 If we want to run the program on a IBM PC, we include the
directive otherwise we won’t.
NOTE:
 The compiler control directives are inside the function. Care
must be taken to put the # character at column one.
#ifdef IBM_PC
{
—— code for IBM_PC
——
}
#else
{
—— code for HP machine
——
}
#endif
#define IBM_PC
Situation 3:
 This situation is similar to the above situation and therefore
the control directives take the following form:
 Group-A lines are included if the customer ABC is defined.
Otherwise, Group-B lines are included.
#idef ABC
Group–A lines
#else
Group–B lines
#endif
 The C preprocessor also supports a more general form of test
condition - #if directive. This take the following form:
 The constant-expression may be any logical expression such as:
 If the result of the constant –expression is nonzero (true), then
all the statements between the #if and #endif are included for
processing ; otherwise they are skipped. The names TEST,
LEVEL , etc., may be defined as macros.
#if constant expression
{
Statement 1;
Statement 2;
——–
}
else
{
Statement 1;
Statement 2;
——–
}
#endif
TEST <=3
(LEVEL == 1|| LEVEL == 2)
MACHINE == ‘A’
 ASNI committee has added some more preprocessor
directives to the existing list given in the table .they
are:
 The ANSI standard also include two new
preprocessor operation:
#elif Provides alternative test facility.
#pragma Specifies certain instructions.
#error Stops compilation when an error occurs.
# Stringizing operator
## Token-pasting operator
 The #elif enables us to establish an “if..else..if..”
sequence for testing multiple conditions. The
general form of use of #elif is:
Syntax:
#if expression 1
statement sequence 1
#elif expression 2
statement sequence 2
………..
………..
#elif expression N
statement sequence N
#endif
Example:
#if MACHINE == HCL
#define FILE”hcl.h”
#elif MACHINE == WIPRO
#define FILE”wipro.h”
………..
………..
#elif MACHINE == DCM
#define FILE”dcm.h”
#endif
#include FILE
 The #pragma is an implementation oriented directive that
allows us to specify various instructions to be given to the
compiler. It takes the following form:
where , name is the name of the pragma we want.
For example, under Microsoft C,
causes loop optimization to be performed. It is ignored, if the
compiler does not recognize it.
#pragma name
#pragma loop_opt(on)
 The #error directives is used to produce diagnostic message during
debugging. The general form is
Syntax:
 When the error directive is encountered, it displays the error
message and terminates processing.
NOTE:
 We have used a special processor operator defined along with if.
defined is a new addition and take a name surrounded by
parentheses. If a compiler does not support this, we can replace it
as follows:
#error error message
Example:
#id !define (FILE_G)
#error NO GRAPHICS FACILITY
# endif
#id !define by #ifndef
#id !define by #ifdef
 An operation # called stringizing operator to be used in the
definition of macro functions.
 This operator allows a formal argument within a macro
definition to be converted to a string.
Example:
• The preprocessor will convert the line - Sum(a+b);
• into - printf(“a+b” ”=%fn”,a+b);
• which is equivalent to - printf(“a+b =%fn”,a+b);
NOTE:
 The ANSI standard also adjacent strings will be concatenated.
#define sum(xy) printf(xy”=%fn”),xy
main()
{
………
Sum(a+b);
……….
}
 The token pasting operator ## defined by ANSI standard enables us to
combine two tokens within a marco definition to form a single token.
Example:
• The preprocessor transforms the statement
printf(“%f”,combine (total,sales));
• into the statement - printf(“%f”,total,sales);
• Consider another macro definition:
#define print(i) printf (“a”#i “=%f”, a##i)
• This marco will convert the statement - print(5)
 into the statement - printf(“a5=%f”,a5)
#define combine (s1,s2) s1 ## s2
main()
{
…………
printf(“%f”,combine (total,sales));
…………
}
Preprocessor

More Related Content

What's hot

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Module 05 Preprocessor and Macros in C
Module 05 Preprocessor and Macros in CModule 05 Preprocessor and Macros in C
Module 05 Preprocessor and Macros in C
Tushar B Kute
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
C++ string
C++ stringC++ string
C++ string
Dheenadayalan18
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
Adnan Khan
 
C Language
C LanguageC Language
C Language
Aakash Singh
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Preprocessors
Preprocessors Preprocessors
Preprocessors
Gourav Arora
 
Types of function call
Types of function callTypes of function call
Types of function call
ArijitDhali
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 

What's hot (20)

File handling in c
File handling in cFile handling in c
File handling in c
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 
Module 05 Preprocessor and Macros in C
Module 05 Preprocessor and Macros in CModule 05 Preprocessor and Macros in C
Module 05 Preprocessor and Macros in C
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
C++ string
C++ stringC++ string
C++ string
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Java program structure
Java program structureJava program structure
Java program structure
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
C Language
C LanguageC Language
C Language
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Function in c
Function in cFunction in c
Function in c
 
Preprocessors
Preprocessors Preprocessors
Preprocessors
 
Types of function call
Types of function callTypes of function call
Types of function call
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 

Similar to Preprocessor

Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Preprocessor directives in c laguage
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguage
Tanmay Modi
 
C programming session6
C programming  session6C programming  session6
C programming session6
Keroles karam khalil
 
Introduction to Preprocessors
Introduction to PreprocessorsIntroduction to Preprocessors
Introduction to Preprocessors
Thesis Scientist Private Limited
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
hasan Mohammad
 
Chapter 13.1.11
Chapter 13.1.11Chapter 13.1.11
Chapter 13.1.11patcha535
 
1 - Preprocessor.pptx
1 - Preprocessor.pptx1 - Preprocessor.pptx
1 - Preprocessor.pptx
AlAmos4
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
Sivakumar R D .
 
Unit 5 Part 1 Macros
Unit 5 Part 1 MacrosUnit 5 Part 1 Macros
Unit 5 Part 1 Macros
Arpana Awasthi
 
Book management system
Book management systemBook management system
Book management system
SHARDA SHARAN
 
C programming
C programmingC programming
C programming
PralhadKhanal1
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
PreProcessorDirective.ppt
PreProcessorDirective.pptPreProcessorDirective.ppt
PreProcessorDirective.ppt
Osmania University
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 
over all view programming to computer
over all view programming to computer over all view programming to computer
over all view programming to computer
muniryaseen
 

Similar to Preprocessor (20)

Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
ANSI C Macros
ANSI C MacrosANSI C Macros
ANSI C Macros
 
Preprocessor directives in c laguage
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguage
 
C programming session6
C programming  session6C programming  session6
C programming session6
 
Introduction to Preprocessors
Introduction to PreprocessorsIntroduction to Preprocessors
Introduction to Preprocessors
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
 
Chapter 13.1.11
Chapter 13.1.11Chapter 13.1.11
Chapter 13.1.11
 
1 - Preprocessor.pptx
1 - Preprocessor.pptx1 - Preprocessor.pptx
1 - Preprocessor.pptx
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
Unit 5 Part 1 Macros
Unit 5 Part 1 MacrosUnit 5 Part 1 Macros
Unit 5 Part 1 Macros
 
Book management system
Book management systemBook management system
Book management system
 
C programming
C programmingC programming
C programming
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
PreProcessorDirective.ppt
PreProcessorDirective.pptPreProcessorDirective.ppt
PreProcessorDirective.ppt
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
over all view programming to computer
over all view programming to computer over all view programming to computer
over all view programming to computer
 

More from lalithambiga kamaraj

Firewall in Network Security
Firewall in Network SecurityFirewall in Network Security
Firewall in Network Security
lalithambiga kamaraj
 
Data Compression in Multimedia
Data Compression in MultimediaData Compression in Multimedia
Data Compression in Multimedia
lalithambiga kamaraj
 
Data CompressionMultimedia
Data CompressionMultimediaData CompressionMultimedia
Data CompressionMultimedia
lalithambiga kamaraj
 
Digital Audio in Multimedia
Digital Audio in MultimediaDigital Audio in Multimedia
Digital Audio in Multimedia
lalithambiga kamaraj
 
Network Security: Physical security
Network Security: Physical security Network Security: Physical security
Network Security: Physical security
lalithambiga kamaraj
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
lalithambiga kamaraj
 
Package in Java
Package in JavaPackage in Java
Package in Java
lalithambiga kamaraj
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Data structure
Data structureData structure
Data structure
lalithambiga kamaraj
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
lalithambiga kamaraj
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
lalithambiga kamaraj
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costs
lalithambiga kamaraj
 
Datamining
DataminingDatamining
Digital Components
Digital ComponentsDigital Components
Digital Components
lalithambiga kamaraj
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
lalithambiga kamaraj
 
Io management disk scheduling algorithm
Io management disk scheduling algorithmIo management disk scheduling algorithm
Io management disk scheduling algorithm
lalithambiga kamaraj
 
Recovery system
Recovery systemRecovery system
Recovery system
lalithambiga kamaraj
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
Inheritance
InheritanceInheritance
Managing console of I/o operations & working with files
Managing console of I/o operations & working with filesManaging console of I/o operations & working with files
Managing console of I/o operations & working with files
lalithambiga kamaraj
 

More from lalithambiga kamaraj (20)

Firewall in Network Security
Firewall in Network SecurityFirewall in Network Security
Firewall in Network Security
 
Data Compression in Multimedia
Data Compression in MultimediaData Compression in Multimedia
Data Compression in Multimedia
 
Data CompressionMultimedia
Data CompressionMultimediaData CompressionMultimedia
Data CompressionMultimedia
 
Digital Audio in Multimedia
Digital Audio in MultimediaDigital Audio in Multimedia
Digital Audio in Multimedia
 
Network Security: Physical security
Network Security: Physical security Network Security: Physical security
Network Security: Physical security
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
 
Package in Java
Package in JavaPackage in Java
Package in Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Data structure
Data structureData structure
Data structure
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costs
 
Datamining
DataminingDatamining
Datamining
 
Digital Components
Digital ComponentsDigital Components
Digital Components
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
Io management disk scheduling algorithm
Io management disk scheduling algorithmIo management disk scheduling algorithm
Io management disk scheduling algorithm
 
Recovery system
Recovery systemRecovery system
Recovery system
 
File management
File managementFile management
File management
 
Inheritance
InheritanceInheritance
Inheritance
 
Managing console of I/o operations & working with files
Managing console of I/o operations & working with filesManaging console of I/o operations & working with files
Managing console of I/o operations & working with files
 

Recently uploaded

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 

Recently uploaded (20)

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 

Preprocessor

  • 2.  Introduction  Macro Substitution  File Inclusion  Compiler Control Directives  ANSI Additions
  • 3.  The C preprocessor provides several tools that are unavailable in other high-level languages.  The programmer can use these tools to make his program easy to read, easy to modify, portable and more efficient.  The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process.
  • 4.
  • 5.  The preprocessor is a program that process the code before it basses through the computer preprocessor directivities are placed in the source program before the main line.  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.  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.
  • 6.
  • 7.
  • 8.  The following section lists down all the important preprocessor directives − Directive Description #define Substitutes a preprocessor macro. #include Inserts a particular header from another file. #undef Undefines a preprocessor macro. #ifdef Returns true if this macro is defined. #ifndef Returns true if this macro is not defined. #if Tests if a compile time condition is true. #else The alternative for #if. #elif #else and #if in one statement. #endif Ends preprocessor conditional. #error Prints error message on stderr. #pragma Issues special commands to the compiler, using a standardized method.
  • 9.  These directivities can be divided into three categories:
  • 10.  Macro substitution is a process where an identifier in a program is replaced by a predefined string composed of one or more identifiers.  It accomplishes this task under the direction of ‘#define’ statement. The general form is  The definition is not terminated by a semicolon. The string may be any text, while the identifier must be a valid C name.  There are different forms of macro substitution. The most common forms are: Syntax: # define identifier string
  • 11.  There are different forms of macro substitutions. The most common forms are 1. Simple macro substitution. 2. Argumented macro substitution. 3. Nested macro substitution.
  • 12.  Simple string replacement is commonly used to define constants. Example :  We have written all macros(identifiers) in capitals. It is a conversion to write all macros in capitals to identify them as symbolic constants.  It will replace all occurrences of ‘M’ with ‘5’, starting from the line of identifier to the end of the program. Example : # define COUNT 100 # define CAPITAL “DELHI” # define M 5 Total = M * value ; Printf(“M = %dn”, M);
  • 13.  These two lines would be changed during pre-processing as follows. Example:  We can use a macro to define almost anything Example:  To build a statement as follows TEST AND PRINT  The preprocessor would translate this line to If(x<y) printf(“very good”); #define TEST if(x<y) #define AND #define PRINT printf(“very good”); Total = 5 * value ; Printf (“M=%dn” , 5);
  • 14.  The preprocessor permits to define more useful form of define replacements. It takes the form Syntax:  There is no space between the macro identifier and the left parentheses. The identifiers f1,f2,…..fn are the formal macro arguments that are analogous to the formal arguments in a function definition.  A macro with arguments is known as a macro call.  When a macro is called, the preprocessor substitutes the string replacing the formal parameters with the actual parameters. # define Identifier(f1,f2,…fn) string
  • 15.  A simple example of a macro with argument is  If the following statement appears in the program  Then the preprocessor would expand this statement as # define CUBE(X) (x*x*x) Volume = CUBE(side); Volume = side * side * side;
  • 16.  Nesting Of Macros use one macro in the definition of another macro. The Macro definitions may be nested.  Consider the following macro definitions.  The preprocessor expands each #define macro until no more macros appear in the test. For example the last definition is first expands into # define SQUARE(x) (x*x) # define CUBE(x) (SQUARE(x)*x) # define SIXTH(x) (CUBE(x)*CUBE(x)) (SQUARE(x)*x) * (SQUARE(x) * x)
  • 17.  Since ‘SQUARE(x)’ is still a macro, it is further expanded into ( ( x * x ) * x ) * ( (x*x)*x) which is finally evaluated as x6.  Macro calls can be nested in much the same fashion as function calls. Example : #define HALF ( (x)/2.0 ) #define Y HALF( HALF(x) )
  • 18.  A defined macro can be undefined using statement Syntax:  This is useful to restrict the definition only to a particular part of the program. # undef identifier
  • 19.  File Inclusion is an external file containing functions or macro definitions can be included as a part of a program.  This is achieved by a preprocessor directive. Syntax:  The ‘file name’ is the name of the file containing the required definitions or functions.  At this point, the preprocessor inserts the entire contents of the file name into the source code of the program.  When the file name is included within the (“ ”) ,then the search for the file is made first in the current directory and then in the standard directories. #include “file name”
  • 20.  Alternatively this directive takes the form  Without (“ ”) in this case this file can include other files. However a file can’t include itself.  We can make use of a definition or function contained in anyone of these files by including them in the program as shown below. #include<stdio.h> #include“shiva.c” #define M 5 main( ) { …………… …………… } #include <file name>
  • 21.  Compiler Control Directives is developing large programs, the ‘C’ pre-processor offers a feature known as conditional compilation.  It can be used to ‘switch’ on or off a particular line or a group of lines in a program.
  • 22.  These compiler control directives are used in different situations. They are: Situation 1:  This situation refers to the conditional definition of a macro. We want to ensure that the macro TEST is always defined, irrespective of whether it has been defined in the header file or not. This can be achieved as follows:  DEFINE.H is the header that is supposed to contain the definition of TEST macro.  The directive #ifndef TEST searches the definition of TEST in the header file and if it is not defined, then all the lines between the #ifndef and the corresponding #endif directive are executed in the program. #include ”DEFINE.H” #ifndef TEST #define TEST 1 #endif
  • 23. Situation 2:  The main concern here is to make the program portable. This can be achieved as shown below:  If we want to run the program on a IBM PC, we include the directive otherwise we won’t. NOTE:  The compiler control directives are inside the function. Care must be taken to put the # character at column one. #ifdef IBM_PC { —— code for IBM_PC —— } #else { —— code for HP machine —— } #endif #define IBM_PC
  • 24. Situation 3:  This situation is similar to the above situation and therefore the control directives take the following form:  Group-A lines are included if the customer ABC is defined. Otherwise, Group-B lines are included. #idef ABC Group–A lines #else Group–B lines #endif
  • 25.  The C preprocessor also supports a more general form of test condition - #if directive. This take the following form:  The constant-expression may be any logical expression such as:  If the result of the constant –expression is nonzero (true), then all the statements between the #if and #endif are included for processing ; otherwise they are skipped. The names TEST, LEVEL , etc., may be defined as macros. #if constant expression { Statement 1; Statement 2; ——– } else { Statement 1; Statement 2; ——– } #endif TEST <=3 (LEVEL == 1|| LEVEL == 2) MACHINE == ‘A’
  • 26.  ASNI committee has added some more preprocessor directives to the existing list given in the table .they are:  The ANSI standard also include two new preprocessor operation: #elif Provides alternative test facility. #pragma Specifies certain instructions. #error Stops compilation when an error occurs. # Stringizing operator ## Token-pasting operator
  • 27.  The #elif enables us to establish an “if..else..if..” sequence for testing multiple conditions. The general form of use of #elif is: Syntax: #if expression 1 statement sequence 1 #elif expression 2 statement sequence 2 ……….. ……….. #elif expression N statement sequence N #endif Example: #if MACHINE == HCL #define FILE”hcl.h” #elif MACHINE == WIPRO #define FILE”wipro.h” ……….. ……….. #elif MACHINE == DCM #define FILE”dcm.h” #endif #include FILE
  • 28.  The #pragma is an implementation oriented directive that allows us to specify various instructions to be given to the compiler. It takes the following form: where , name is the name of the pragma we want. For example, under Microsoft C, causes loop optimization to be performed. It is ignored, if the compiler does not recognize it. #pragma name #pragma loop_opt(on)
  • 29.  The #error directives is used to produce diagnostic message during debugging. The general form is Syntax:  When the error directive is encountered, it displays the error message and terminates processing. NOTE:  We have used a special processor operator defined along with if. defined is a new addition and take a name surrounded by parentheses. If a compiler does not support this, we can replace it as follows: #error error message Example: #id !define (FILE_G) #error NO GRAPHICS FACILITY # endif #id !define by #ifndef #id !define by #ifdef
  • 30.  An operation # called stringizing operator to be used in the definition of macro functions.  This operator allows a formal argument within a macro definition to be converted to a string. Example: • The preprocessor will convert the line - Sum(a+b); • into - printf(“a+b” ”=%fn”,a+b); • which is equivalent to - printf(“a+b =%fn”,a+b); NOTE:  The ANSI standard also adjacent strings will be concatenated. #define sum(xy) printf(xy”=%fn”),xy main() { ……… Sum(a+b); ………. }
  • 31.  The token pasting operator ## defined by ANSI standard enables us to combine two tokens within a marco definition to form a single token. Example: • The preprocessor transforms the statement printf(“%f”,combine (total,sales)); • into the statement - printf(“%f”,total,sales); • Consider another macro definition: #define print(i) printf (“a”#i “=%f”, a##i) • This marco will convert the statement - print(5)  into the statement - printf(“a5=%f”,a5) #define combine (s1,s2) s1 ## s2 main() { ………… printf(“%f”,combine (total,sales)); ………… }