Jun 28, 2014

C Programming #29: Constant Macros

Following article will discuss how macros are used instead of literal constants.

Consider the following example :




#include <stdio.h>
int main()
{
   int i;

   printf("Multiplication Table\n");
   for(i = 0; i < 10; i++) {
      printf("10 * %d = %d\n", i, i *10); 
   }
   printf("Square of 10 is %d\n", 10 * 10);
   printf("Cube of 10 is %d\n", 10 * 10 * 10);

   return 0;
}

Output of the program is


Multiplication Table
10 * 0 = 0
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
Square of 10 is 100
Cube of 10 is 1000
Say now we want to modify the above program to find multiplication table for number 8. Then we need to modify the code in 10 different place replacing number 10 with 8 in each place.

Instead of we manually replacing it we could tell compiler to use Macro (also called #define).

Syntax of macro :

#define identifier token_string

Above macro replaces all the occurrences of identifier with token_string. Identifier should be valid token. You can find more information in following link regarding valid token. token_string can be anything.

Lets re-write the above program using macro


#include <stdio.h>
#define NUM 8
int main()
{
   int i;

   printf("Multiplication Table\n");
   for(i = 0; i < NUM; i++) {
      printf("NUM * %d = %d\n", i, i * NUM); 
   }
   printf("Square of NUM is %d\n", NUM * NUM);
   printf("Cube of NUM is %d\n", NUM * NUM * NUM);

   return 0;
}

Output of which is


Multiplication Table
NUM * 0 = 0
NUM * 1 = 8
NUM * 2 = 16
NUM * 3 = 24
NUM * 4 = 32
NUM * 5 = 40
NUM * 6 = 48
NUM * 7 = 56
Square of NUM is 64
Cube of NUM is 512

Ohhh what just happened!!!! In few places compiler replaced NUM with 8 while in some place it did not. Reason for this behavior is, compiler does not replace identifier if it appears in
  1. comment
  2. string
  3. part of a longer identifier.

Hence re-writing it again


#include <stdio.h>
#define NUM 8
int main()
{
   int i;

   printf("Multiplication Table\n");
   for(i = 0; i < NUM; i++) {
      printf("%d * %d = %d\n", NUM, i, i * NUM); 
   }
   printf("Square of %d is %d\n", NUM, NUM * NUM);
   printf("Cube of %d is %d\n", NUM, NUM * NUM * NUM);

   return 0;
}

Output of which is


Multiplication Table
8 * 0 = 0
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
Square of 8 is 64
Cube of 8 is 512
Some other examples of #define are

#define PI 3.14
#define WELCOME_MSG "Hello and Welcome"
#define PI 22/7

This is how Macro as constant works. There is yet another function like use of macro which will be covered later in C Programming #36: Parameterised Macro.

Quiz - Not yet written yet
Next Article - C Programming #30: Constant - enum
Previous Article - C Programming #28: Decision Making - goto
All Article - C Programming

No comments :

Post a Comment