SlideShare a Scribd company logo
THE PREPROCESSOR
Contents
• The preprocessor introduction
• #include
• #define (Symbolic Constants)
• #define (Macro)
• Conditional compilation
• #error and #pragma
• # and ## Operators
• Line Numbers
• Predefined Symbolic Constants
• Assertions
2
Introduction
– Occurs before program compiled
• Inclusion of external files (#include <stdio.h>)
• Definition of symbolic constants (#define max 100)
• Macros
• Conditional compilation (#ifdef #elif #endif …)
• Conditional execution
– All directives begin with #
– Directives not C++ statements
• Do not end with ;
– Preprocessor is the text replacement
3
#include
– Puts copy of file in place of directive
• Seen many times in example code
– Two forms
• #include <filename>
– For standard library header files in SDK
– Searches predestinated directories
• #include "filename"
– Searches in current directory
– Normally used for programmer-defined files
4
#include
• Example
– Before preprocess
– After preprocess
After preprocess
math.cpp
void foo_1();
void foo_2()
{
printf(“#include me“);
}
// ---------------------------------------
void foo()
{
return;
}
Before preprocess
my_header.h
void foo_1();
void foo_2()
{
printf(“#include me“);
}
math.cpp
#include "my_header.h“
void foo()
{
return;
} 5
#define
Symbolic constants
– Symbolic constants
• Constants represented as symbols
• All occurrences replaced in preprocess before compiling
– Format
#defineidentifier replacement-text
#definePI 3.14159
– Everything to right of identifier replaces text
#definePI =3.14159
Replaces PI with "=3.14159"
– Cannot redefine symbolic constants
6
#define
Symbolic constants
#include <stdio.h>
#define PI 3.14
#define LEVEL =1
void main()
{
float pi = PI;
int lv = LEVEL;
}
#include <stdio.h>
void main()
{
float pi = 3.14;
int lv = =1;
}
7
#define
Symbolic constants
• Advantages
– Takes no memory
• Disadvantages
– Name not be seen by debugger (replacement
text)
– No type checking (not safe).
– Using static constant instead.
8
#define
Macros
• Macro
– Operation specified in #define
– Intended for legacy C programs
– Macro without arguments
• Treated like a symbolic constant
– Macro with arguments
• Arguments substituted for replacement text
• Macro expanded
– Performs a text substitution
• No data type checking
9
#define
Macros
• Example
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
area = CIRCLE_AREA( 4 );
becomes
area = ( 3.14159 * ( 4 ) * ( 4 ) );
• Use parentheses
– Without them,
#define CIRCLE_AREA( x ) PI * x * x
area = CIRCLE_AREA( c + 2 );
becomes
area = 3.14159 * c + 2 * c + 2;
which evaluates incorrectly
10
#define
Macros
• Multiple arguments
#define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
rectArea = RECTANGLE_AREA( a + 4, b + 7 );
becomes
rectArea = ( ( a + 4 ) * ( b + 7 ) );
• #undef
– Undefines symbolic constant or macro
– Can later be redefined
11
*Conditional compilation
• Control preprocessor directives and compilation
– Cannot evaluate cast expressions, sizeof, enumeration constants
• Structure similar to if
#if !defined( NULL )
#define NULL 0
#endif
– Determines if symbolic constant NULL defined
– If NULL defined,
• defined( NULL ) evaluates to 1
• #define statement skipped
– Otherwise
• #define statement used
– Every #if ends with #endif
12
*Conditional compilation
• Can use else
#else
#elif is "else if“
• Abbreviations
#ifdef short for
#if defined(name)
#ifndef short for
#if !defined(name)
13
*Conditional compilation
• "Comment out" code
– Cannot use /* ... */ with C-style comments
• Cannot nest /* */
– Instead, use
#if 0
code commented out
#endif
– To enable code, change 0 to 1
14
*Conditional compilation
• Debugging
#define DEBUG 1
#ifdef DEBUG
cerr << "Variable x = " << x << endl;
#endif
– Defining DEBUG enables code
– After code corrected
• Remove #define statement
• Debugging statements are now ignored
15
#error and #pragma
• #error tokens
– Prints implementation-dependent message
– Tokens are groups of characters separated by
spaces
• #error 1 - Out of range error has 6 tokens
– Compilation may stop (depends on compiler)
• #pragma tokens
– Actions depend on compiler
– May use compiler-specific options
– Unrecognized #pragmas are ignored
16
# and ## operators
• # operator
– Replacement text token converted to string with
quotes
#define HELLO( x ) cout << "Hello, " #x << endl;
– HELLO( JOHN ) becomes
• cout << "Hello, " "John" << endl;
• Same as cout << "Hello, John" << endl;
• ## operator
– Concatenates two tokens
#define TOKENCONCAT( x, y ) x ## y
– TOKENCONCAT( O, K ) becomes
• OK
17
Line numbers
• #line
– Renumbers subsequent code lines, starting
with integer
• #line 100
– File name can be included
– #line 100 "file1.cpp"
• Next source code line is numbered 100
• For error purposes, file name is "file1.cpp"
• Can make syntax errors more meaningful
• Line numbers do not appear in source file
18
Predefined symbolic constants
Symbolic
constant Description
__LINE__ The line number of the current source code line (an integer constant).
__FILE__ The presumed name of the source file (a string).
__DATE__ The date the source file is compiled (a string of the form "Mmm dd yyyy"
such as "Jan 19 2001").
__TIME__ The time the source file is compiled (a string literal of the form
"hh:mm:ss").
Five predefined symbolic constants
Cannot be used in #define or #undef
19
Assertions
• assert is a macro
– Header <cassert>
– Tests value of an expression
• If 0 (false) prints error message, calls abort
– Terminates program, prints line number and file
– Good for checking for illegal values
• If 1 (true), program continues as normal
– assert( x <= 10 );
• To remove assert statements
– No need to delete them manually
– #define NDEBUG
• All subsequent assert statements ignored
20

More Related Content

What's hot (20)

PDF
File Handling in C Programming
RavindraSalunke3
 
PDF
6 preprocessor macro header
hasan Mohammad
 
PPTX
Programming Fundamentals lecture 5
REHAN IJAZ
 
DOCX
Unit 5 quesn b ans5
Sowri Rajan
 
PPTX
Basics of c Nisarg Patel
TechNGyan
 
PPT
Introduction to c
sunila tharagaturi
 
PDF
88 c-programs
Leandro Schenone
 
PDF
Deep C
Olve Maudal
 
PPTX
1 introduction to c program
NishmaNJ
 
PPTX
Python Session - 4
AnirudhaGaikwad4
 
PPT
C tutorial
Diwakar_singh1989
 
PPTX
Subroutines in perl
sana mateen
 
PDF
Function in C
Dr. Abhineet Anand
 
PDF
Functions and modules in python
Karin Lagesen
 
PPTX
Presentation on function
Abu Zaman
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPT
Prsentation on functions
Alisha Korpal
 
TXT
Unix
Shohan Ahmed
 
PPTX
Built in function
MD. Rayhanul Islam Sayket
 
PPTX
predefined and user defined functions
Swapnil Yadav
 
File Handling in C Programming
RavindraSalunke3
 
6 preprocessor macro header
hasan Mohammad
 
Programming Fundamentals lecture 5
REHAN IJAZ
 
Unit 5 quesn b ans5
Sowri Rajan
 
Basics of c Nisarg Patel
TechNGyan
 
Introduction to c
sunila tharagaturi
 
88 c-programs
Leandro Schenone
 
Deep C
Olve Maudal
 
1 introduction to c program
NishmaNJ
 
Python Session - 4
AnirudhaGaikwad4
 
C tutorial
Diwakar_singh1989
 
Subroutines in perl
sana mateen
 
Function in C
Dr. Abhineet Anand
 
Functions and modules in python
Karin Lagesen
 
Presentation on function
Abu Zaman
 
Python functions
Prof. Dr. K. Adisesha
 
Prsentation on functions
Alisha Korpal
 
Built in function
MD. Rayhanul Islam Sayket
 
predefined and user defined functions
Swapnil Yadav
 

Viewers also liked (16)

PDF
Informatika 10-klas-morze-2010
freegdz
 
PDF
wilder_teaching_statement
Michael Wilder
 
PDF
A la-ética
ssergior
 
PDF
Khudozhnya kultura-10-klas-klimova
freegdz
 
PDF
Geometriya 11-klas-bevz-2011
freegdz
 
PDF
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
freegdz
 
PDF
Українська література 6 клас Авраменко 2014 от Freegdz.com
freegdz
 
PPTX
Mpl 9 oop
AHHAAH
 
PPTX
Location-based Learning
Michael Wilder
 
DOCX
Target audiece profile
OllieHumphrisVyners
 
PDF
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
kadri yusuf
 
PPTX
Media Evaluation Question 5
OllieHumphrisVyners
 
PPT
Java non access modifiers
Srinivas Reddy
 
PPTX
Lesiones pulmonares cavitadas
Carlos Gonzalez Andrade
 
PPTX
2017 01-15 Meetup Slides
Vancouver Disciplined Trading Hub (VDTH)
 
Informatika 10-klas-morze-2010
freegdz
 
wilder_teaching_statement
Michael Wilder
 
A la-ética
ssergior
 
Khudozhnya kultura-10-klas-klimova
freegdz
 
Geometriya 11-klas-bevz-2011
freegdz
 
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
freegdz
 
Українська література 6 клас Авраменко 2014 от Freegdz.com
freegdz
 
Mpl 9 oop
AHHAAH
 
Location-based Learning
Michael Wilder
 
Target audiece profile
OllieHumphrisVyners
 
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
kadri yusuf
 
Media Evaluation Question 5
OllieHumphrisVyners
 
Java non access modifiers
Srinivas Reddy
 
Lesiones pulmonares cavitadas
Carlos Gonzalez Andrade
 
Ad

Similar to Preprocessor (20)

PPTX
introduction of c langauge(I unit)
Prashant Sharma
 
PPTX
Pre processor directives in c
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
1 - Preprocessor.pptx
AlAmos4
 
PPT
Preprocessors
Gourav Arora
 
PPTX
Preprocessor
lalithambiga kamaraj
 
PPT
Preprocessors
Koganti Ravikumar
 
PPT
PreProcessorDirective.ppt
Osmania University
 
PPTX
UNIT 4A-preprocessor.pptx for c language and basic knowledge
2024163103shubham
 
PDF
Preprocessor
Learn By Watch
 
PDF
ANSI C Macros
Srikrishnan Suresh
 
PPT
Unit 5 cspc
BBDITM LUCKNOW
 
PPTX
Preprocessor directives in c laguage
Tanmay Modi
 
PDF
0100_Embeded_C_CompilationProcess.pdf
KhaledIbrahim10923
 
PDF
05 -working_with_the_preproce
Hector Garzo
 
PDF
3 1. preprocessor, math, stdlib
웅식 전
 
PDF
Chapter 13.1.11
patcha535
 
PPT
Lecture 21 - Preprocessor and Header File
Md. Imran Hossain Showrov
 
PDF
Introduction to Preprocessors
Thesis Scientist Private Limited
 
PDF
C programming session6
Keroles karam khalil
 
introduction of c langauge(I unit)
Prashant Sharma
 
1 - Preprocessor.pptx
AlAmos4
 
Preprocessors
Gourav Arora
 
Preprocessor
lalithambiga kamaraj
 
Preprocessors
Koganti Ravikumar
 
PreProcessorDirective.ppt
Osmania University
 
UNIT 4A-preprocessor.pptx for c language and basic knowledge
2024163103shubham
 
Preprocessor
Learn By Watch
 
ANSI C Macros
Srikrishnan Suresh
 
Unit 5 cspc
BBDITM LUCKNOW
 
Preprocessor directives in c laguage
Tanmay Modi
 
0100_Embeded_C_CompilationProcess.pdf
KhaledIbrahim10923
 
05 -working_with_the_preproce
Hector Garzo
 
3 1. preprocessor, math, stdlib
웅식 전
 
Chapter 13.1.11
patcha535
 
Lecture 21 - Preprocessor and Header File
Md. Imran Hossain Showrov
 
Introduction to Preprocessors
Thesis Scientist Private Limited
 
C programming session6
Keroles karam khalil
 
Ad

Recently uploaded (20)

PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 

Preprocessor

  • 2. Contents • The preprocessor introduction • #include • #define (Symbolic Constants) • #define (Macro) • Conditional compilation • #error and #pragma • # and ## Operators • Line Numbers • Predefined Symbolic Constants • Assertions 2
  • 3. Introduction – Occurs before program compiled • Inclusion of external files (#include <stdio.h>) • Definition of symbolic constants (#define max 100) • Macros • Conditional compilation (#ifdef #elif #endif …) • Conditional execution – All directives begin with # – Directives not C++ statements • Do not end with ; – Preprocessor is the text replacement 3
  • 4. #include – Puts copy of file in place of directive • Seen many times in example code – Two forms • #include <filename> – For standard library header files in SDK – Searches predestinated directories • #include "filename" – Searches in current directory – Normally used for programmer-defined files 4
  • 5. #include • Example – Before preprocess – After preprocess After preprocess math.cpp void foo_1(); void foo_2() { printf(“#include me“); } // --------------------------------------- void foo() { return; } Before preprocess my_header.h void foo_1(); void foo_2() { printf(“#include me“); } math.cpp #include "my_header.h“ void foo() { return; } 5
  • 6. #define Symbolic constants – Symbolic constants • Constants represented as symbols • All occurrences replaced in preprocess before compiling – Format #defineidentifier replacement-text #definePI 3.14159 – Everything to right of identifier replaces text #definePI =3.14159 Replaces PI with "=3.14159" – Cannot redefine symbolic constants 6
  • 7. #define Symbolic constants #include <stdio.h> #define PI 3.14 #define LEVEL =1 void main() { float pi = PI; int lv = LEVEL; } #include <stdio.h> void main() { float pi = 3.14; int lv = =1; } 7
  • 8. #define Symbolic constants • Advantages – Takes no memory • Disadvantages – Name not be seen by debugger (replacement text) – No type checking (not safe). – Using static constant instead. 8
  • 9. #define Macros • Macro – Operation specified in #define – Intended for legacy C programs – Macro without arguments • Treated like a symbolic constant – Macro with arguments • Arguments substituted for replacement text • Macro expanded – Performs a text substitution • No data type checking 9
  • 10. #define Macros • Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); becomes area = ( 3.14159 * ( 4 ) * ( 4 ) ); • Use parentheses – Without them, #define CIRCLE_AREA( x ) PI * x * x area = CIRCLE_AREA( c + 2 ); becomes area = 3.14159 * c + 2 * c + 2; which evaluates incorrectly 10
  • 11. #define Macros • Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) rectArea = RECTANGLE_AREA( a + 4, b + 7 ); becomes rectArea = ( ( a + 4 ) * ( b + 7 ) ); • #undef – Undefines symbolic constant or macro – Can later be redefined 11
  • 12. *Conditional compilation • Control preprocessor directives and compilation – Cannot evaluate cast expressions, sizeof, enumeration constants • Structure similar to if #if !defined( NULL ) #define NULL 0 #endif – Determines if symbolic constant NULL defined – If NULL defined, • defined( NULL ) evaluates to 1 • #define statement skipped – Otherwise • #define statement used – Every #if ends with #endif 12
  • 13. *Conditional compilation • Can use else #else #elif is "else if“ • Abbreviations #ifdef short for #if defined(name) #ifndef short for #if !defined(name) 13
  • 14. *Conditional compilation • "Comment out" code – Cannot use /* ... */ with C-style comments • Cannot nest /* */ – Instead, use #if 0 code commented out #endif – To enable code, change 0 to 1 14
  • 15. *Conditional compilation • Debugging #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif – Defining DEBUG enables code – After code corrected • Remove #define statement • Debugging statements are now ignored 15
  • 16. #error and #pragma • #error tokens – Prints implementation-dependent message – Tokens are groups of characters separated by spaces • #error 1 - Out of range error has 6 tokens – Compilation may stop (depends on compiler) • #pragma tokens – Actions depend on compiler – May use compiler-specific options – Unrecognized #pragmas are ignored 16
  • 17. # and ## operators • # operator – Replacement text token converted to string with quotes #define HELLO( x ) cout << "Hello, " #x << endl; – HELLO( JOHN ) becomes • cout << "Hello, " "John" << endl; • Same as cout << "Hello, John" << endl; • ## operator – Concatenates two tokens #define TOKENCONCAT( x, y ) x ## y – TOKENCONCAT( O, K ) becomes • OK 17
  • 18. Line numbers • #line – Renumbers subsequent code lines, starting with integer • #line 100 – File name can be included – #line 100 "file1.cpp" • Next source code line is numbered 100 • For error purposes, file name is "file1.cpp" • Can make syntax errors more meaningful • Line numbers do not appear in source file 18
  • 19. Predefined symbolic constants Symbolic constant Description __LINE__ The line number of the current source code line (an integer constant). __FILE__ The presumed name of the source file (a string). __DATE__ The date the source file is compiled (a string of the form "Mmm dd yyyy" such as "Jan 19 2001"). __TIME__ The time the source file is compiled (a string literal of the form "hh:mm:ss"). Five predefined symbolic constants Cannot be used in #define or #undef 19
  • 20. Assertions • assert is a macro – Header <cassert> – Tests value of an expression • If 0 (false) prints error message, calls abort – Terminates program, prints line number and file – Good for checking for illegal values • If 1 (true), program continues as normal – assert( x <= 10 ); • To remove assert statements – No need to delete them manually – #define NDEBUG • All subsequent assert statements ignored 20