Macro Substitution using #define in C

By: Kamini Emailed: 1673 times Printed: 2153 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A definition has the form
   #define name replacement text
It calls for a macro substitution of the simplest kind - subsequent occurrences of the token name will be replaced by the replacement text. The name in a #define has the same form as a variable name; the replacement text is arbitrary. Normally the replacement text is the rest of the line, but a long definition may be continued onto several lines by placing a \ at the end of each line to be continued. The scope of a name defined with #define is from its point of definition to the end of the source file being compiled. A definition may use previous definitions. Substitutions are made only for tokens, and do not take place within quoted strings. For example, if YES is a defined name, there would be no substitution in printf("YES") or in YESMAN.

Any name may be defined with any replacement text. For example

   #define  forever  for (;;)    /* infinite loop */
defines a new word, forever, for an infinite loop.

It is also possible to define macros with arguments, so the replacement text can be different for different calls of the macro. As an example, define a macro called max:

   #define  max(A, B)  ((A) > (B) ? (A) : (B))
Although it looks like a function call, a use of max expands into in-line code. Each occurrence of a formal parameter (here A or B) will be replaced by the corresponding actual argument. Thus the line
   x = max(p+q, r+s);
will be replaced by the line
   x = ((p+q) > (r+s) ? (p+q) : (r+s));
So long as the arguments are treated consistently, this macro will serve for any data type; there is no need for different kinds of max for different data types, as there would be with functions.

If you examine the expansion of max, you will notice some pitfalls. The expressions are evaluated twice; this is bad if they involve side effects like increment operators or input and output. For instance

   max(i++, j++)  /* WRONG */
will increment the larger twice. Some care also has to be taken with parentheses to make sure the order of evaluation is preserved; consider what happens when the macro
   #define square(x)  x * x  /* WRONG */
is invoked as square(z+1).

Nonetheless, macros are valuable. One practical example comes from <stdio.h>, in which getchar and putchar are often defined as macros to avoid the run-time overhead of a function call per character processed. The functions in <ctype.h> are also usually implemented as macros.

Names may be undefined with #undef, usually to ensure that a routine is really a function, not a macro:

   #undef getchar

   int getchar(void) { ... }
Formal parameters are not replaced within quoted strings. If, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to make, for example, a debugging print macro:
   #define  dprint(expr)   printf(#expr " = %g\n", expr)
When this is invoked, as in
   dprint(x/y)
the macro is expanded into
   printf("x/y" " = &g\n", x/y);
and the strings are concatenated, so the effect is
   printf("x/y = &g\n", x/y);
Within the actual argument, each " is replaced by \" and each \ by \\, so the result is a legal string constant.

The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned. For example, the macro paste concatenates its two arguments:

   #define  paste(front, back)  front ## back
so paste(name, 1) creates the token name1.

C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Kamini
Importing the Certificate Reply from the CA example using keytool in Java
The switch Statement example in Java
Joins example in SQL
ERRNO.H Header File in C
XDoclet struts-config.xml in Struts
Macro Substitution using #define in C
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Do while Loops in C
Functions in C
Opening files for read and write in C++
Operator Precedence in C++
StringItem sample program in J2ME
AWT-based applications with a User Interface Window in Java
store() and load() example in Java
Stray or Dangling Pointers in C++

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
UNIX read and write system calls sample program in C
Find square and square root for a given number in C
lseek() sample program in C
Character Arrays in C
Using memset(), memcpy(), and memmove() in C
scanf and sscanf sample program in C
Open, Creat, Close, Unlink system calls sample program in C
Listing Files and Directories sample program in C
Using free() Function in C
Printing a simple histogram in C
goto and labels in C
Macro Substitution using #define in C
Fopen and Getc implementation program in C
assert() Function Example program in C
perror() Function - example program in C
Most Emailed Articles (in C)
Passing pointer to a function in C
File Copying in C
Arithmetic Operators in C
scanf and sscanf sample program in C
assert() Function Example program in C
perror() Function - example program in C
Infix to Prefix And Postfix in C
External Variables and Scope in C
Constants and escape sequences in C
register Variables in C
Tutorial on Complicated Declarations in C
Standard Input and Output in C
lseek() sample program in C
Listing Files and Directories sample program in C
Using memset(), memcpy(), and memmove() in C