L9 Preprocessors in C
L9 Preprocessors in C
Content for the slides have been taken from the various sources and
from the reference books.
• The C preprocessor searches for the macro name MSSG and substitutes the
message "I understand the use of #define\n" in the printf ().
#define
• The can have macro expansions of any sort. Here are some more examples-
• #define AND &&
• #define OR II
• #define BEGIN main(){
• #define END }
• #define INFINITE while(1)
• ~define NEW_LINE printf("\n");
• #define ERROR printf("An error has occurred\n");
• Here is a semicolon in the last two directives. This semicolon is just a part of
the macro_expansion.
• Now whenever we write NEW_LINE or ERROR in the program, they will be
replaced by printf calls and the terminating semicolon.
#define
• C preprocessor will simply replace the macro_name with the macro_expansion
and the macro_expansion can be any text. So it is our responsibility to see that
after replacement the resulting code is valid in C. For example if we define a
macro MAX like this-
• #define MAX 5;
• Now consider this declaration statement
• int arr[MAX];
• This will be translated by the preprocessor as
• int arr[5;]; and this is not valid in C.
• If the macro_name appears inside a character constant, string constant or a
comment then it is not replaced and is left as it is. For example-
• #define SUN 2
• #define WINDOWS 3
• printf("Rays of SUN are coming through the WINDOWS");
• The #define directive can also be used to define macros with arguments. The general
syntax is-
• #define macro_name(arg 1, arg2, ......) macro_expansion
• Here argl, arg2 .... are the fonnal arguments.
• The macro_name is replaced with the macro_expansion and the formal arguments are
replaced by the corresponding actual arguments supplied in the macro call.
Macros with Arguments
Macros with Arguments
< Questions?