SlideShare a Scribd company logo
1 of 20
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)

File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
 
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
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
Deep C
Deep CDeep C
Deep C
 
1 introduction to c program
1 introduction to c program1 introduction to c program
1 introduction to c program
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
C tutorial
C tutorialC tutorial
C tutorial
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Function in C
Function in CFunction in C
Function in C
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Python functions
Python functionsPython functions
Python functions
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Unix
UnixUnix
Unix
 
Built in function
Built in functionBuilt in function
Built in function
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 

Viewers also liked

Informatika 10-klas-morze-2010
Informatika 10-klas-morze-2010Informatika 10-klas-morze-2010
Informatika 10-klas-morze-2010freegdz
 
wilder_teaching_statement
wilder_teaching_statementwilder_teaching_statement
wilder_teaching_statementMichael Wilder
 
A la-ética
A la-éticaA la-ética
A la-éticassergior
 
Khudozhnya kultura-10-klas-klimova
Khudozhnya kultura-10-klas-klimovaKhudozhnya kultura-10-klas-klimova
Khudozhnya kultura-10-klas-klimovafreegdz
 
Geometriya 11-klas-bevz-2011
Geometriya 11-klas-bevz-2011Geometriya 11-klas-bevz-2011
Geometriya 11-klas-bevz-2011freegdz
 
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
Istoriya ukrajini-10-klas-kulchickijj-lebedehvaIstoriya ukrajini-10-klas-kulchickijj-lebedehva
Istoriya ukrajini-10-klas-kulchickijj-lebedehvafreegdz
 
Українська література 6 клас Авраменко 2014 от Freegdz.com
Українська література 6 клас Авраменко 2014 от Freegdz.comУкраїнська література 6 клас Авраменко 2014 от Freegdz.com
Українська література 6 клас Авраменко 2014 от Freegdz.comfreegdz
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oopAHHAAH
 
Location-based Learning
Location-based LearningLocation-based Learning
Location-based LearningMichael Wilder
 
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
Permendikbud70 2013 kd-strukturkurikulum-smk-makPermendikbud70 2013 kd-strukturkurikulum-smk-mak
Permendikbud70 2013 kd-strukturkurikulum-smk-makkadri yusuf
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiersSrinivas Reddy
 

Viewers also liked (16)

Informatika 10-klas-morze-2010
Informatika 10-klas-morze-2010Informatika 10-klas-morze-2010
Informatika 10-klas-morze-2010
 
wilder_teaching_statement
wilder_teaching_statementwilder_teaching_statement
wilder_teaching_statement
 
A la-ética
A la-éticaA la-ética
A la-ética
 
Khudozhnya kultura-10-klas-klimova
Khudozhnya kultura-10-klas-klimovaKhudozhnya kultura-10-klas-klimova
Khudozhnya kultura-10-klas-klimova
 
Geometriya 11-klas-bevz-2011
Geometriya 11-klas-bevz-2011Geometriya 11-klas-bevz-2011
Geometriya 11-klas-bevz-2011
 
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
Istoriya ukrajini-10-klas-kulchickijj-lebedehvaIstoriya ukrajini-10-klas-kulchickijj-lebedehva
Istoriya ukrajini-10-klas-kulchickijj-lebedehva
 
Українська література 6 клас Авраменко 2014 от Freegdz.com
Українська література 6 клас Авраменко 2014 от Freegdz.comУкраїнська література 6 клас Авраменко 2014 от Freegdz.com
Українська література 6 клас Авраменко 2014 от Freegdz.com
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
 
Location-based Learning
Location-based LearningLocation-based Learning
Location-based Learning
 
Target audiece profile
Target audiece profileTarget audiece profile
Target audiece profile
 
299 2015 norme-sicurezza_i
299   2015   norme-sicurezza_i299   2015   norme-sicurezza_i
299 2015 norme-sicurezza_i
 
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
Permendikbud70 2013 kd-strukturkurikulum-smk-makPermendikbud70 2013 kd-strukturkurikulum-smk-mak
Permendikbud70 2013 kd-strukturkurikulum-smk-mak
 
Media Evaluation Question 5
Media Evaluation Question 5Media Evaluation Question 5
Media Evaluation Question 5
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
Lesiones pulmonares cavitadas
Lesiones pulmonares cavitadasLesiones pulmonares cavitadas
Lesiones pulmonares cavitadas
 
2017 01-15 Meetup Slides
2017 01-15 Meetup Slides2017 01-15 Meetup Slides
2017 01-15 Meetup Slides
 

Similar to Preprocessor

Similar to Preprocessor (20)

Preprocessors
Preprocessors Preprocessors
Preprocessors
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
C
CC
C
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C++Basics.pdf
C++Basics.pdfC++Basics.pdf
C++Basics.pdf
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineni
 
CPlusPus
CPlusPusCPlusPus
CPlusPus
 
introduction of c langauge(I unit)
introduction of c langauge(I unit)introduction of c langauge(I unit)
introduction of c langauge(I unit)
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptC++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
Gun make
Gun makeGun make
Gun make
 
C Programming
C ProgrammingC Programming
C Programming
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 

Recently uploaded

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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