Preprocessor Directives or commands (Video)
• Preprocessor directives starts with the symbol #
• No semicolon after the preprocessor statement
o #include<stdio.h>
• They are processed before the program runs
There are 3 directives
1. #include – loads in needed header files
2. symbolic constants – identifier for a value
o #define NUM 10
o Note that the variable name NUM is in caps, by convention the
variable names are caps.
o They are called symbolic constants because of text substitution is
done before program runs.
o See the lesson on variables on constants pages 3 and 4 which
explains the #define
Example program
#include<stdio.h>
#define NUM 10
#define TAXRATE 8.75
int main()
{
//Declaration of variables
int quantity, value;
float price, tax;
//data/input
value = 5;
price = 10;
//Calculation/Processing
tax = TAXRATE / 100 * price;
quantity = NUM + 3;
value = value * TAXRATE/100;
//output
printf("The tax is $%.2f\n", tax);
printf("The quantity is %d\n", quantity);
printf("The value is %f\n", value);
return 0;
}
Use symbolic constants for example like tax rates, because tax rates seldom
change.
3. Macro – identifier for a formula
o #define SUM (a + b + c)
o text substitution is done before program runs.
Example program
#include<stdio.h>
#define SUM (a + b + c)
#define AVG SUM / (float)3
int main()
{
//Declaration of variables
int a, b, c;
//data/input
printf("Enter 3 numbers : ");
scanf("%d%d%d", &a, &b, &c);
//output
printf("The sum is %d\n", SUM);
printf("The average is %f\n", AVG);
return 0;
}
Be careful when you use macro as it may give you unexpected results. For this
class, you should avoid using macros and put your formulas in the program where
it should belong in the calculation section.