Hi there,
#defines can be used to define constants or macros. The four in your code are defining macros. A macro is something like a function.
To understand #defines and other preprocessor directives, you have to know that they are never seen by the compiler. When you compile a C program, the code is first run through a preprocessor which finds any #defines and #includes, and then replaces any instances of them in the source code with the contents of the #define or the contents of the file named by the #include.
For instance, if you do the following:
Code:
#include <stdio.h>
int abs(int n) {
return n > 0 ? n : -n;
}
void main(void) {
int i;
for (i = -10; i <= 10; i++) {
printf("%d\n", abs(i));
}
}
. . .then the only thing that the preprocessor does is replace the #include line with the contents of the file stdio.h. abs() is a function here and is called once per loop.
However, you could also do this:
Code:
#include <stdio.h>
#define ABS(n) (n > 0 ? n : -n)
void main(void) {
int i;
for (i = -10; i <= 10; i++) {
printf("%d\n", ABS(i));
}
}
In this case, the preprocessor replaces the #include line with the contents of stdio.h, but it also replaces every instance of "ABS(n)" in the code with "(n > 0 ? n : -n)", where n can be any integer.
In the first example, a function is defined and called on each loop. In the second example, a macro is defined, and the loop is rewritten to:
Code:
for (i = -10; i <= 10; i++) {
printf("%d\n", (n > 0 ? n : -n));
}
. . .before the compiler ever sees it. Macros can be useful in a lot of ways; in the above example it makes sense to use macros since the cost of including the code is lower than the cost of calling a function on each loop.
You should Google on terms like "c #define" and "c #ifdef" to learn more. The C preprocessor is a powerful tool.
Regards,
Torben
[Edit: 3v0 beat me to it.
]