Jagannath Institute of Management Sciences
Vasant Kunj-II, New Delhi - 110070
Subject Name: Programming In C
Department of Information Technology
Created By: Dr. Arpana Chaturvedi
@Dr. Arpana Chaturvedi
Subject: Programming In C
Topic: Unit V- Part I
Preprocessor Directives
@Dr. Arpana Chaturvedi
Topics to be Covered
▰ Introduction to Preprocessor
▰ Macros
▰ Header file inclusion
▰ Conditional compilation
▰ Other directives
@Dr. Arpana Chaturvedi
Introduction to Preprocessor in C
@Dr. Arpana Chaturvedi
C PREPROCESSOR DIRECTIVES
▰ The C pre-processor is a micro processor that is used by compiler to transform your
code before compilation. This process is called pre-processing.
▰ It is called micro pre-processor because it allows us to add macros.
▰ It must be the first nonblank character, and for readability, a pre-processor directive
should begin in the first column
▰ Note: Pre-processor directives are executed before compilation. All commands used in
pre-processor are called pre-processor directives and they begin with “#” symbol.
@Dr. Arpana Chaturvedi
C PREPROCESSOR DIRECTIVES
@Dr. Arpana Chaturvedi
List of Pre-Processor Directives in C
Preprocessor Syntax/Description
Macro
Syntax: #define
This macro defines constant value and can be any of the basic
data types.
Header file
inclusion
Syntax: #include <file_name>
The source code of the file “file_name” is included in the main
program at the specified place.
Conditional
compilation
Syntax: #ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in source program
before compilation with respect to the condition.
Other directives
Syntax: #undef, #pragma
#undef is used to undefine a defined macro variable. #Pragma is
used to call a function before and after main function in a C
program.
@Dr. Arpana Chaturvedi
Pre-Processor Directives in C
Sr.No. Directive & Description
1 #define
Substitutes a preprocessor macro.
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.
5 #ifndef
Returns true if this macro is not defined.
@Dr. Arpana Chaturvedi
Pre-Processor Directives in C
Sr.No. Directive & Description
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
@Dr. Arpana Chaturvedi
Preprocessor Operators
@Dr. Arpana Chaturvedi
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 Welcome you to JIMS Vasant Kunj-II!n")
Preprocessor Operators
@Dr. Arpana Chaturvedi
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.
#include <stdio.h>
#define message_for(a, b) 
printf(#a " and " #b ": We
Welcome you to JIMS
Vasant Kunj-II!n")
void main(void) {
message_for(Amit, Aman);
getch();
}
Output:
Amit and Aman: We Welcome you to
JIMS Vasant Kunj-II!
Preprocessor Operators
@Dr. Arpana Chaturvedi
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.
#include <stdio.h>
#define tokenpaster(n) 
printf ("token" #n " = %d", token##n)
void main(void) {
int token34 = 40;
tokenpaster(34);
getch();
}
Output:
token34 = 40
The 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.
Preprocessor Operators
@Dr. Arpana Chaturvedi
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).
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE “How are
you doing?”
#endif
void main(void) {
printf(“Hello Aman: %sn",
MESSAGE);
getch();
}
Output:
Hello Aman: How are you
doing?
Preprocessor Operators
@Dr. Arpana Chaturvedi
Parameterized Macros
▰ One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros.
int square(int x) {
return x * x;
}
We can rewrite 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.
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
void main(void) {
printf("Max between 20 and 10 is
%dn", MAX(10, 20));
getch();
}
Output:
Max between 20 and 10 is 20
1. Macros in C
@ Dr.Arpana Chaturvedi
Macro in C
▰ Macros are generally used to define constant values that are being used repeatedly in
program.
▰ Macros can even accept arguments and such macros are known as function-like macros.
▰ It can be useful if tokens are concatenated into code to simplify some complex declarations.
▰ Macros provide text replacement functionality at pre-processing time.
▰ A macro is a name given to a block of C statements as a pre-processor directive.
▰ Being a pre-processor, the block of code is communicated to the compiler before entering into
the actual coding (main () function).
▰ A macro is defined with the preprocessor directive, #define
@Dr. Arpana Chaturvedi
Macro in C
▰ A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
▰ Object-like Macros
▰ Function-like Macros
@Dr. Arpana Chaturvedi
Object-like Macros in C
▰ The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
▰ #define PI 3.14
▰ Here, PI is the macro name which will be replaced by the value 3.14.
@Dr. Arpana Chaturvedi
Function-like Macros in C
@Dr. Arpana Chaturvedi
▰ The function-like macro looks like function call. For example:
▰ #define MIN(a,b) ((a)<(b)?(a):(b))
▰ Here, MIN is the macro name.
▰ Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros in C
@Dr. Arpana Chaturvedi
▰ ANSI C defines many predefined macros that can be used in c program.
Sr.No. Macro & Description
1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.
2 __TIME__
The current time as a character literal in "HH:MM:SS" format.
3 __FILE__
This contains the current filename as a string literal.
4 __LINE__
This contains the current line number as a decimal constant.
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
Example of Predefined Macro
@Dr. Arpana Chaturvedi
#define Macro
@Dr. Arpana Chaturvedi
▰ In the C Programming Language, the #define directive allows the definition of macros within
your source code.
▰ These macro definitions allow constant values to be declared for use throughout your code.
▰ Macro definitions are not variables and cannot be changed by your program code like
variables.
▰ You generally use this syntax when creating constants that represent numbers, strings or
expressions.
Syntax of #define Macro
@Dr. Arpana Chaturvedi
▰ Constant
▰ #define CNAME value
▰ OR
▰ #define CNAME (expression)
▰ CNAME
▰ The name of the constant. Most C programmers define their constant names in uppercase,
but it is not a requirement of the C Language.
▰ value
▰ The value of the constant.
▰ expression
▰ Expression whose value is assigned to the constant. The expression must be enclosed in
parentheses if it contains operators.
▰ Note: Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.
Syntax of #define Macro
@Dr. Arpana Chaturvedi
▰ Number
▰ #define directive to define a numeric constant:
▰ Example: The constant named AGE would contain the value of 10.
▰ #define AGE 10
▰ String
▰ #define directive to define a string constant.
▰ Example: The constant called NAME would contain the value of "C Programming".
▰ #define NAME "C Programming"
▰ Expression
▰ Example :The #define directive to define a constant using an expression.
▰ #define GRADE (20 / 2)
Syntax of #define Macro
@Dr. Arpana Chaturvedi
Output:
Syntax of #define Macro
@Dr. Arpana Chaturvedi
1. #include <stdio.h>
2. #define height 100
3. #define number 3.14
4. #define letter 'A'
5. #define letter_sequence "ABC"
6. #define backslash_char '?'
7. void main()
8. {
9. printf("value of height : %d n", height );
10. printf("value of number : %f n", number );
11. printf("value of letter : %c n", letter );
12. printf("value of letter_sequence : %s n", letter_sequence);
13. printf("value of backslash_char : %c n", backslash_char);
14.}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence :
ABC
value of backslash_char : ?
2. Header File Inclusion
@ Dr.Arpana Chaturvedi
#include Preprocessor Directive
@Dr. Arpana Chaturvedi
▰ #include Pre-processor directive is used to include header files in C Program.
▰ Header File is a file with extension .h which contains C function declarations and macro
definitions.
▰ These functions can be with any number of source files in which the header file is included
with #include Pre-processor directives.
▰ In the C Programming Language, the #include directive tells the Pre-processor to insert the
contents of another file into the source code at the point where the #include directive is found.
▰ Include directives are typically used to include the C header files for C functions that are held
outside of the current source file.
▰ By the use of #include directive, we provide information to the pre-processor where to look for
the header files.
▰ If included file is not found, compiler renders error.
Types of Header Files for Inclusion
@Dr. Arpana Chaturvedi
There are two types of header files:
▰ User Defined Header Files
The files that the programmer writes
▰ System Defined Header Files
The files that comes with your compiler.
Syntax to include Header Files in C
@Dr. Arpana Chaturvedi
Syntax of User Defined Header File:
#include "file“
▰ This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file.
▰ You can prepend directories to this list with the -I option while compiling your source code
Syntax of System Defined Header File:
#include <file>
▰ This form is used for system header files.
▰ It searches for a file named 'file' in a standard list of system directories.
▰ You can prepend directories to this list with the -I option while compiling your source code.
Header File Inclusion: Note and Example
@Dr. Arpana Chaturvedi
Note
▰ The difference between these two syntaxes is subtle but important.
▰ If a header file is included within <>, the preprocessor will search a predetermined directory
path to locate the header file.
▰ If the header file is enclosed in "", the preprocessor will look for the header file in the same
directory as the source file.
Example
▰ The #include directive to include:
▰ stdio.h header file which is required to use the printf and scanf standard C library function
▰ conio.h header file which is required to use getch standard library function.
Example of #include Directive
@Dr. Arpana Chaturvedi
Output:
@Dr. Arpana Chaturvedi
3. Conditional Compilation
@ Dr.Arpana Chaturvedi
Conditional compilation in C language
@Dr. Arpana Chaturvedi
▰ C preprocessor recognizes a number of directives that support conditional compilation.
▰ As the name implies that the code is compiled and the inclusion or exclusion of a section of a
program text depends upon the outcome of conditional test performed by the preprocessor
i.e. if certain condition(s) hold true.
▰ Normally we use if keyword for checking some condition so we have to use something
different so that compiler can determine whether to compile the code or not.
▰ It is the process of selecting the source code conditionally from the program and sending to
the compiler using preprocessor statements .
Few Conditional Compilation Directives
@Dr. Arpana Chaturvedi
▰ Few Conditional Compilation Directives are:
▰ #if--#endif
▰ #if..#else..#endif
▰ #if..#elif…#else…#endif
▰ #ifdef---#endif
▰ #ifndef----#endif
#if--#endif preprocessor conditional
statement in C
@Dr. Arpana Chaturvedi
▰ Here the preprocessor selection statement #if checks the condition.
▰ If it is true or a non-zero then statements between #if and #else are sent to the compiler.
▰ If it is false or a zero then statements between #else and #endif are sent to the compiler
Example of #if--#endif in C
@Dr. Arpana Chaturvedi
Output of of #if--#endif in C
@Dr. Arpana Chaturvedi
These Conditional Compilation Directives allow us to
include certain portion of the code depending upon the
output of constant expression.
#elif Conditional Directive in C
@Dr. Arpana Chaturvedi
▰ In the C Programming Language, the #elif provides an alternate action when used with the #if,
#ifdef, or #ifndef directives.
▰ The preprocessor will include the C source code that follows the #elif statement when the
condition of the preceding #if, #ifdef or #ifndef directive evaluates to false and the #elif
condition evaluates to true.
▰ The #elif directive can be thought of as #else if.
▰ Syntax
▰ The syntax for the #elif directive in the C language is:
▰ #elif conditional_expression
▰ conditional_expression
▰ Expression that must evaluate to true for the preprocessor to include the C source code into
the compiled application.
▰ Note
▰ The #elif directive must be closed by an #endif directive.
#elif Conditional Directive in C
@Dr. Arpana Chaturvedi
▰ Expression allows only constant expression.
▰ #elif directive means “else if”
▰ #elif Establishes an if-else-if chain for multiple compilation options.
▰ Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is
compiled , then it jumps to #endif.
▰ Result of the Expression is FALSE , then Corresponding #elif condition is tested , if true the the
block followed by that elif is Compiled otherwise it checks for Next condition followed by next
elif statement
▰ #endif is the end of #if statement
Syntax of #elif Conditional Directive in C
@Dr. Arpana Chaturvedi
Syntax of #if--#elif---#else..#endif
▰ #if Expression1
▰ Statement_block 1;
▰ #elif Expression2
▰ Statement_block 2;
▰ #elif Expression3
▰ Statement_block 3;
▰ #else
▰ Statement_block 4;
▰ #endif
Example of #elif Conditional Directive in C
@Dr. Arpana Chaturvedi
Output
Example of #elif Conditional Directive in C
@Dr. Arpana Chaturvedi
Output
#undef Conditional Directive in C
@Dr. Arpana Chaturvedi
▰ In the C Programming Language, the #undef directive tells the preprocessor to remove all
definitions for the specified macro.
▰ A macro can be redefined after it has been removed by the #undef directive.
▰ Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.
Syntax
▰ #undef macro_definition
macro_definition
▰ The name of the macro which will be removed by the preprocessor.
Example of #undef Conditional Directive in C
@Dr. Arpana Chaturvedi
Output
#ifdef Conditional Directive in C
@Dr. Arpana Chaturvedi
▰ In the C Programming Language, the #ifdef directive allows for conditional compilation.
▰ The preprocessor determines if the provided macro exists before including the subsequent code
in the compilation process.
Syntax
▰ #ifdef macro_definition
macro_definition
▰ The macro definition that must be defined for the preprocessor to include the C source code
into the compiled application.
Note
▰ The #ifdef directive must be closed by an #endif directive.
Example of #ifdef Conditional Directive in C
@Dr. Arpana Chaturvedi
Output
EXAMPLE PROGRAM FOR #IFDEF,
#ELSE AND #ENDIF IN C
@Dr. Arpana Chaturvedi
OUTPUT:
MAKS is defined. So, this line will be added in this C file
• “#ifdef” directive
checks whether
particular macro is
defined or not. If it
is defined, “If”
clause statements
are included in
source file.
• Otherwise, “else”
clause statements
are included in
source file for
compilation and
execution.
EXAMPLE PROGRAM FOR #IFNDEF
AND #ENDIF IN C:
@Dr. Arpana Chaturvedi
• #ifndef exactly acts
as reverse as #ifdef
directive. If particular
macro is not defined,
“If” clause
statements are
included in source
file.
• Otherwise, else
clause statements
are included in
source file for
compilation and
execution.
OUTPUT:
SUBJECTM is not defined. So, now we are going to define
here
EXAMPLE PROGRAM FOR #IF, #ELSE AND
#ENDIF IN C:
@Dr. Arpana Chaturvedi
• “If” clause statement
is included in source
file if given condition
is true.
• Otherwise, else
clause statement is
included in source
file for compilation
and execution.
OUTPUT:
This line will be added in this C file since MARKS = 100
EXAMPLE PROGRAM FOR UNDEF IN C
LANGUAGE:
@Dr. Arpana Chaturvedi
OUTPUT:
First defined value for MARKS : 100
The value of MARKS after undef & redefine : 600
This directive
undefines existing
macro in the
program.
4. Pragma
@ Dr.Arpana Chaturvedi
EXAMPLE PROGRAM FOR PRAGMA IN C
LANGUAGE:
@Dr. Arpana Chaturvedi
Pragma is used to call a
function before and after main
function in a C program.
OUTPUT:
Function1 is called before
main function call
Now we are in main function
Function2 is called just before
end of main function
Macro and Functions
@ Dr.Arpana Chaturvedi
Difference Between Macro And Functions In C
@Dr. Arpana Chaturvedi
MACRO FUNCTION
Macro is Preprocessed Function is Compiled
No Type Checking is done in Macro Type Checking is Done in Function
Using Macro increases the code length Using Function keeps the code length unaffected
Use of macro can lead to side effect at later stages Functions do not lead to any side effect in any case
Speed of Execution using Macro is Faster Speed of Execution using Function is Slower
Before Compilation, macro name is replaced by
macro value
During function call, transfer of control takes place
Macros are useful when small code is repeated
many times
Functions are useful when large code is to be
written
Macro does not check any Compile-Time Errors Function checks Compile-Time Errors
Example Showing Difference Between Macro And
Functions
@Dr. Arpana Chaturvedi
Macros are pre-processed which means that all the macros would be processed
before your program compiles. However, functions are not preprocessed but
compiled.
Example Of Function To Differentiate From
Macro In C
@Dr. Arpana Chaturvedi
Output
Conclusion of Example
@Dr. Arpana Chaturvedi
• This shows that the macros are preprocessed while functions are not.
• In macros, no type checking (incompatible operand, etc.) is done and thus use of
macros can lead to errors/side-effects in some cases.
• However, this is not the case with functions.
• Also, macros do not check for compilation error (if any).
Function Macro Can Also Be Used In C
@Dr. Arpana Chaturvedi
Output
Function Used In Place Of Macro In C
@Dr. Arpana Chaturvedi
Output
Conclusion of Example
@Dr. Arpana Chaturvedi
• Macros are usually one liner. However, they can consist of more than one line.
There are no such constraints in functions.
• The speed at which macros and functions differs. Macros are typically faster than
functions as they don’t involve actual function call overhead.
Advantages – Disadvantages
of Macro
Advantages Of Using Macro In C
@Dr. Arpana Chaturvedi
▰ A macro is a name given to a block of the code which can be substituted where the code
snippet is to be used for more than once.
A) The speed of the execution of the program is the major advantage of using a macro.
B) It saves a lot of time that is spent by the compiler for invoking / calling the functions.
C) It reduces the length of the program
Disadvantages Of Macros
@Dr. Arpana Chaturvedi
▰ Macros are no longer recommended as they cause following issues. There is a better way in
modern compilers that is inline functions and const variable.
a) There is no type checking
b) Difficult to debug as they cause simple replacement.
c) Macro don’t have namespace, so a macro in one section of code can affect
other section.
d) Macros can cause side effects
Thank You !!
@Dr. Arpana Chaturvedi

Unit 5 Part 1 Macros

  • 1.
    Jagannath Institute ofManagement Sciences Vasant Kunj-II, New Delhi - 110070 Subject Name: Programming In C Department of Information Technology Created By: Dr. Arpana Chaturvedi @Dr. Arpana Chaturvedi
  • 2.
    Subject: Programming InC Topic: Unit V- Part I Preprocessor Directives @Dr. Arpana Chaturvedi
  • 3.
    Topics to beCovered ▰ Introduction to Preprocessor ▰ Macros ▰ Header file inclusion ▰ Conditional compilation ▰ Other directives @Dr. Arpana Chaturvedi
  • 4.
    Introduction to Preprocessorin C @Dr. Arpana Chaturvedi
  • 5.
    C PREPROCESSOR DIRECTIVES ▰The C pre-processor is a micro processor that is used by compiler to transform your code before compilation. This process is called pre-processing. ▰ It is called micro pre-processor because it allows us to add macros. ▰ It must be the first nonblank character, and for readability, a pre-processor directive should begin in the first column ▰ Note: Pre-processor directives are executed before compilation. All commands used in pre-processor are called pre-processor directives and they begin with “#” symbol. @Dr. Arpana Chaturvedi
  • 6.
  • 7.
    List of Pre-ProcessorDirectives in C Preprocessor Syntax/Description Macro Syntax: #define This macro defines constant value and can be any of the basic data types. Header file inclusion Syntax: #include <file_name> The source code of the file “file_name” is included in the main program at the specified place. Conditional compilation Syntax: #ifdef, #endif, #if, #else, #ifndef Set of commands are included or excluded in source program before compilation with respect to the condition. Other directives Syntax: #undef, #pragma #undef is used to undefine a defined macro variable. #Pragma is used to call a function before and after main function in a C program. @Dr. Arpana Chaturvedi
  • 8.
    Pre-Processor Directives inC Sr.No. Directive & Description 1 #define Substitutes a preprocessor macro. 2 #include Inserts a particular header from another file. 3 #undef Undefines a preprocessor macro. 4 #ifdef Returns true if this macro is defined. 5 #ifndef Returns true if this macro is not defined. @Dr. Arpana Chaturvedi
  • 9.
    Pre-Processor Directives inC Sr.No. Directive & Description 6 #if Tests if a compile time condition is true. 7 #else The alternative for #if. 8 #elif #else and #if in one statement. 9 #endif Ends preprocessor conditional. 10 #error Prints error message on stderr. @Dr. Arpana Chaturvedi
  • 10.
    Preprocessor Operators @Dr. ArpanaChaturvedi 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 Welcome you to JIMS Vasant Kunj-II!n")
  • 11.
    Preprocessor Operators @Dr. ArpanaChaturvedi 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. #include <stdio.h> #define message_for(a, b) printf(#a " and " #b ": We Welcome you to JIMS Vasant Kunj-II!n") void main(void) { message_for(Amit, Aman); getch(); } Output: Amit and Aman: We Welcome you to JIMS Vasant Kunj-II!
  • 12.
    Preprocessor Operators @Dr. ArpanaChaturvedi 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. #include <stdio.h> #define tokenpaster(n) printf ("token" #n " = %d", token##n) void main(void) { int token34 = 40; tokenpaster(34); getch(); } Output: token34 = 40 The 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.
  • 13.
    Preprocessor Operators @Dr. ArpanaChaturvedi 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). #include <stdio.h> #if !defined (MESSAGE) #define MESSAGE “How are you doing?” #endif void main(void) { printf(“Hello Aman: %sn", MESSAGE); getch(); } Output: Hello Aman: How are you doing?
  • 14.
    Preprocessor Operators @Dr. ArpanaChaturvedi Parameterized Macros ▰ One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. int square(int x) { return x * x; } We can rewrite 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. #include <stdio.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) void main(void) { printf("Max between 20 and 10 is %dn", MAX(10, 20)); getch(); } Output: Max between 20 and 10 is 20
  • 15.
    1. Macros inC @ Dr.Arpana Chaturvedi
  • 16.
    Macro in C ▰Macros are generally used to define constant values that are being used repeatedly in program. ▰ Macros can even accept arguments and such macros are known as function-like macros. ▰ It can be useful if tokens are concatenated into code to simplify some complex declarations. ▰ Macros provide text replacement functionality at pre-processing time. ▰ A macro is a name given to a block of C statements as a pre-processor directive. ▰ Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). ▰ A macro is defined with the preprocessor directive, #define @Dr. Arpana Chaturvedi
  • 17.
    Macro in C ▰A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros: ▰ Object-like Macros ▰ Function-like Macros @Dr. Arpana Chaturvedi
  • 18.
    Object-like Macros inC ▰ The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example: ▰ #define PI 3.14 ▰ Here, PI is the macro name which will be replaced by the value 3.14. @Dr. Arpana Chaturvedi
  • 19.
    Function-like Macros inC @Dr. Arpana Chaturvedi ▰ The function-like macro looks like function call. For example: ▰ #define MIN(a,b) ((a)<(b)?(a):(b)) ▰ Here, MIN is the macro name. ▰ Visit #define to see the full example of object-like and function-like macros.
  • 20.
    C Predefined Macrosin C @Dr. Arpana Chaturvedi ▰ ANSI C defines many predefined macros that can be used in c program. Sr.No. Macro & Description 1 __DATE__ The current date as a character literal in "MMM DD YYYY" format. 2 __TIME__ The current time as a character literal in "HH:MM:SS" format. 3 __FILE__ This contains the current filename as a string literal. 4 __LINE__ This contains the current line number as a decimal constant. 5 __STDC__ Defined as 1 when the compiler complies with the ANSI standard.
  • 21.
    Example of PredefinedMacro @Dr. Arpana Chaturvedi
  • 22.
    #define Macro @Dr. ArpanaChaturvedi ▰ In the C Programming Language, the #define directive allows the definition of macros within your source code. ▰ These macro definitions allow constant values to be declared for use throughout your code. ▰ Macro definitions are not variables and cannot be changed by your program code like variables. ▰ You generally use this syntax when creating constants that represent numbers, strings or expressions.
  • 23.
    Syntax of #defineMacro @Dr. Arpana Chaturvedi ▰ Constant ▰ #define CNAME value ▰ OR ▰ #define CNAME (expression) ▰ CNAME ▰ The name of the constant. Most C programmers define their constant names in uppercase, but it is not a requirement of the C Language. ▰ value ▰ The value of the constant. ▰ expression ▰ Expression whose value is assigned to the constant. The expression must be enclosed in parentheses if it contains operators. ▰ Note: Do NOT put a semicolon character at the end of #define statements. This is a common mistake.
  • 24.
    Syntax of #defineMacro @Dr. Arpana Chaturvedi ▰ Number ▰ #define directive to define a numeric constant: ▰ Example: The constant named AGE would contain the value of 10. ▰ #define AGE 10 ▰ String ▰ #define directive to define a string constant. ▰ Example: The constant called NAME would contain the value of "C Programming". ▰ #define NAME "C Programming" ▰ Expression ▰ Example :The #define directive to define a constant using an expression. ▰ #define GRADE (20 / 2)
  • 25.
    Syntax of #defineMacro @Dr. Arpana Chaturvedi Output:
  • 26.
    Syntax of #defineMacro @Dr. Arpana Chaturvedi 1. #include <stdio.h> 2. #define height 100 3. #define number 3.14 4. #define letter 'A' 5. #define letter_sequence "ABC" 6. #define backslash_char '?' 7. void main() 8. { 9. printf("value of height : %d n", height ); 10. printf("value of number : %f n", number ); 11. printf("value of letter : %c n", letter ); 12. printf("value of letter_sequence : %s n", letter_sequence); 13. printf("value of backslash_char : %c n", backslash_char); 14.} OUTPUT: value of height : 100 value of number : 3.140000 value of letter : A value of letter_sequence : ABC value of backslash_char : ?
  • 27.
    2. Header FileInclusion @ Dr.Arpana Chaturvedi
  • 28.
    #include Preprocessor Directive @Dr.Arpana Chaturvedi ▰ #include Pre-processor directive is used to include header files in C Program. ▰ Header File is a file with extension .h which contains C function declarations and macro definitions. ▰ These functions can be with any number of source files in which the header file is included with #include Pre-processor directives. ▰ In the C Programming Language, the #include directive tells the Pre-processor to insert the contents of another file into the source code at the point where the #include directive is found. ▰ Include directives are typically used to include the C header files for C functions that are held outside of the current source file. ▰ By the use of #include directive, we provide information to the pre-processor where to look for the header files. ▰ If included file is not found, compiler renders error.
  • 29.
    Types of HeaderFiles for Inclusion @Dr. Arpana Chaturvedi There are two types of header files: ▰ User Defined Header Files The files that the programmer writes ▰ System Defined Header Files The files that comes with your compiler.
  • 30.
    Syntax to includeHeader Files in C @Dr. Arpana Chaturvedi Syntax of User Defined Header File: #include "file“ ▰ This form is used for header files of your own program. It searches for a file named 'file' in the directory containing the current file. ▰ You can prepend directories to this list with the -I option while compiling your source code Syntax of System Defined Header File: #include <file> ▰ This form is used for system header files. ▰ It searches for a file named 'file' in a standard list of system directories. ▰ You can prepend directories to this list with the -I option while compiling your source code.
  • 31.
    Header File Inclusion:Note and Example @Dr. Arpana Chaturvedi Note ▰ The difference between these two syntaxes is subtle but important. ▰ If a header file is included within <>, the preprocessor will search a predetermined directory path to locate the header file. ▰ If the header file is enclosed in "", the preprocessor will look for the header file in the same directory as the source file. Example ▰ The #include directive to include: ▰ stdio.h header file which is required to use the printf and scanf standard C library function ▰ conio.h header file which is required to use getch standard library function.
  • 32.
    Example of #includeDirective @Dr. Arpana Chaturvedi
  • 33.
  • 34.
    3. Conditional Compilation @Dr.Arpana Chaturvedi
  • 35.
    Conditional compilation inC language @Dr. Arpana Chaturvedi ▰ C preprocessor recognizes a number of directives that support conditional compilation. ▰ As the name implies that the code is compiled and the inclusion or exclusion of a section of a program text depends upon the outcome of conditional test performed by the preprocessor i.e. if certain condition(s) hold true. ▰ Normally we use if keyword for checking some condition so we have to use something different so that compiler can determine whether to compile the code or not. ▰ It is the process of selecting the source code conditionally from the program and sending to the compiler using preprocessor statements .
  • 36.
    Few Conditional CompilationDirectives @Dr. Arpana Chaturvedi ▰ Few Conditional Compilation Directives are: ▰ #if--#endif ▰ #if..#else..#endif ▰ #if..#elif…#else…#endif ▰ #ifdef---#endif ▰ #ifndef----#endif
  • 37.
    #if--#endif preprocessor conditional statementin C @Dr. Arpana Chaturvedi ▰ Here the preprocessor selection statement #if checks the condition. ▰ If it is true or a non-zero then statements between #if and #else are sent to the compiler. ▰ If it is false or a zero then statements between #else and #endif are sent to the compiler
  • 38.
    Example of #if--#endifin C @Dr. Arpana Chaturvedi
  • 39.
    Output of of#if--#endif in C @Dr. Arpana Chaturvedi These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression.
  • 40.
    #elif Conditional Directivein C @Dr. Arpana Chaturvedi ▰ In the C Programming Language, the #elif provides an alternate action when used with the #if, #ifdef, or #ifndef directives. ▰ The preprocessor will include the C source code that follows the #elif statement when the condition of the preceding #if, #ifdef or #ifndef directive evaluates to false and the #elif condition evaluates to true. ▰ The #elif directive can be thought of as #else if. ▰ Syntax ▰ The syntax for the #elif directive in the C language is: ▰ #elif conditional_expression ▰ conditional_expression ▰ Expression that must evaluate to true for the preprocessor to include the C source code into the compiled application. ▰ Note ▰ The #elif directive must be closed by an #endif directive.
  • 41.
    #elif Conditional Directivein C @Dr. Arpana Chaturvedi ▰ Expression allows only constant expression. ▰ #elif directive means “else if” ▰ #elif Establishes an if-else-if chain for multiple compilation options. ▰ Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is compiled , then it jumps to #endif. ▰ Result of the Expression is FALSE , then Corresponding #elif condition is tested , if true the the block followed by that elif is Compiled otherwise it checks for Next condition followed by next elif statement ▰ #endif is the end of #if statement
  • 42.
    Syntax of #elifConditional Directive in C @Dr. Arpana Chaturvedi Syntax of #if--#elif---#else..#endif ▰ #if Expression1 ▰ Statement_block 1; ▰ #elif Expression2 ▰ Statement_block 2; ▰ #elif Expression3 ▰ Statement_block 3; ▰ #else ▰ Statement_block 4; ▰ #endif
  • 43.
    Example of #elifConditional Directive in C @Dr. Arpana Chaturvedi Output
  • 44.
    Example of #elifConditional Directive in C @Dr. Arpana Chaturvedi Output
  • 45.
    #undef Conditional Directivein C @Dr. Arpana Chaturvedi ▰ In the C Programming Language, the #undef directive tells the preprocessor to remove all definitions for the specified macro. ▰ A macro can be redefined after it has been removed by the #undef directive. ▰ Once a macro is undefined, an #ifdef directive on that macro will evaluate to false. Syntax ▰ #undef macro_definition macro_definition ▰ The name of the macro which will be removed by the preprocessor.
  • 46.
    Example of #undefConditional Directive in C @Dr. Arpana Chaturvedi Output
  • 47.
    #ifdef Conditional Directivein C @Dr. Arpana Chaturvedi ▰ In the C Programming Language, the #ifdef directive allows for conditional compilation. ▰ The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process. Syntax ▰ #ifdef macro_definition macro_definition ▰ The macro definition that must be defined for the preprocessor to include the C source code into the compiled application. Note ▰ The #ifdef directive must be closed by an #endif directive.
  • 48.
    Example of #ifdefConditional Directive in C @Dr. Arpana Chaturvedi Output
  • 49.
    EXAMPLE PROGRAM FOR#IFDEF, #ELSE AND #ENDIF IN C @Dr. Arpana Chaturvedi OUTPUT: MAKS is defined. So, this line will be added in this C file • “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are included in source file. • Otherwise, “else” clause statements are included in source file for compilation and execution.
  • 50.
    EXAMPLE PROGRAM FOR#IFNDEF AND #ENDIF IN C: @Dr. Arpana Chaturvedi • #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause statements are included in source file. • Otherwise, else clause statements are included in source file for compilation and execution. OUTPUT: SUBJECTM is not defined. So, now we are going to define here
  • 51.
    EXAMPLE PROGRAM FOR#IF, #ELSE AND #ENDIF IN C: @Dr. Arpana Chaturvedi • “If” clause statement is included in source file if given condition is true. • Otherwise, else clause statement is included in source file for compilation and execution. OUTPUT: This line will be added in this C file since MARKS = 100
  • 52.
    EXAMPLE PROGRAM FORUNDEF IN C LANGUAGE: @Dr. Arpana Chaturvedi OUTPUT: First defined value for MARKS : 100 The value of MARKS after undef & redefine : 600 This directive undefines existing macro in the program.
  • 53.
  • 54.
    EXAMPLE PROGRAM FORPRAGMA IN C LANGUAGE: @Dr. Arpana Chaturvedi Pragma is used to call a function before and after main function in a C program. OUTPUT: Function1 is called before main function call Now we are in main function Function2 is called just before end of main function
  • 55.
    Macro and Functions @Dr.Arpana Chaturvedi
  • 56.
    Difference Between MacroAnd Functions In C @Dr. Arpana Chaturvedi MACRO FUNCTION Macro is Preprocessed Function is Compiled No Type Checking is done in Macro Type Checking is Done in Function Using Macro increases the code length Using Function keeps the code length unaffected Use of macro can lead to side effect at later stages Functions do not lead to any side effect in any case Speed of Execution using Macro is Faster Speed of Execution using Function is Slower Before Compilation, macro name is replaced by macro value During function call, transfer of control takes place Macros are useful when small code is repeated many times Functions are useful when large code is to be written Macro does not check any Compile-Time Errors Function checks Compile-Time Errors
  • 57.
    Example Showing DifferenceBetween Macro And Functions @Dr. Arpana Chaturvedi Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not preprocessed but compiled.
  • 58.
    Example Of FunctionTo Differentiate From Macro In C @Dr. Arpana Chaturvedi Output
  • 59.
    Conclusion of Example @Dr.Arpana Chaturvedi • This shows that the macros are preprocessed while functions are not. • In macros, no type checking (incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. • However, this is not the case with functions. • Also, macros do not check for compilation error (if any).
  • 60.
    Function Macro CanAlso Be Used In C @Dr. Arpana Chaturvedi Output
  • 61.
    Function Used InPlace Of Macro In C @Dr. Arpana Chaturvedi Output
  • 62.
    Conclusion of Example @Dr.Arpana Chaturvedi • Macros are usually one liner. However, they can consist of more than one line. There are no such constraints in functions. • The speed at which macros and functions differs. Macros are typically faster than functions as they don’t involve actual function call overhead.
  • 63.
  • 64.
    Advantages Of UsingMacro In C @Dr. Arpana Chaturvedi ▰ A macro is a name given to a block of the code which can be substituted where the code snippet is to be used for more than once. A) The speed of the execution of the program is the major advantage of using a macro. B) It saves a lot of time that is spent by the compiler for invoking / calling the functions. C) It reduces the length of the program
  • 65.
    Disadvantages Of Macros @Dr.Arpana Chaturvedi ▰ Macros are no longer recommended as they cause following issues. There is a better way in modern compilers that is inline functions and const variable. a) There is no type checking b) Difficult to debug as they cause simple replacement. c) Macro don’t have namespace, so a macro in one section of code can affect other section. d) Macros can cause side effects
  • 66.
    Thank You !! @Dr.Arpana Chaturvedi