[courses] [C] lesson7/8 - Various things
KWMelvin
kwmelvin at intrex.net
Tue Nov 12 17:58:09 EST 2002
On Tue, Nov 12, 2002 at 03:25:56PM -0500, Morgon Kanter wrote:
> 1st: I'm still having a bit of trouble understanding the stuff with the
> pre-processor (mainly #define, #ifdef/#ifndef). Could you please explain it
> again?
>
> Morgon
Hello Morgan,
The preprocessor is like a special text editor. With a simple #define
it does a search and replace. For example, in the following program,
the defined pattern FOO is replaced with the digit 3 when the preprocessor
runs before the program is compiled:
/***********************************************************/
/* define1.c */
#include <stdio.h>
#define SIZE 3
int main(void)
{
int box;
box = SIZE;
printf("%d\n", box);
return 0;
}
/***********************************************************/
In a small program like this, there really isn't much sense in having
a #define in the program; but in a larger program, where FOO might be
in several places in the program, doing a manual search and replace
might lead to errors. With a #define, all you have to do is change
the value in one place, and it is effectively changed everywhere that
the definition occurs.
So another way of explaining a #define is that it has this general form:
#define PATTERN replacement
The replacement can be any text. The text will be inserted in the program
wherever the PATTERN is, for example:
#define PATTERN for(i = 0; i < sizeof(array); i++)
might be used like this:
/*
** Clear the array
*/
PATTERN {
data[i] = 0;
}
After the preprocessor ran, the code would look like this for the compiler:
for(i = 0; i < sizeof(array); i++) {
data[i] = 0;
}
The #define macro can also take parameters. The example given is:
#define SQR(x) ((x) * (x)) /* Square a number */
When used, the macro will replace `x' (in SQR(x)) with the text of
the following argument:
SQR(5) expands to ((5) * (5))
The #ifdef, #endif, #ifndef, and #else are used in conditional
compilation. I've seen this occur in source code that is written
for multiple platforms, like DOS and UNIX. The best way to understand
this stuff is to look at a working example. Unfortunately, the chapter
in the book was sorely lacking in working examples, and I can't come
up with one off the top of my head. Maybe someone on the list can write
an example that illustrates conditional compilation using the above
preprocessor directives? If I find one in my books, I'll post it.
Happy Programming!
--
K
More information about the Courses
mailing list