This blog is under construction

Wednesday, 23 May 2012

#define directive in C

#define directive is used to create definition for a macro.  Below is the general form of macro

#define <MACRO_NAME>  <MACRO_VALUE>

Usually, macro names are written in upper case characters.  During preprocessing, the macro names in program would be replaced by value of the macro.

Consider the following example,
char first_name[20];
char last_name[20];
char course[20];
char school[20];

Above are the declaration for four different character arrays, each can hold 20 characters. Suppose, if user wants to change the size of all character array from 20 to 30, then user has to modify array index of all the above character arrays.  Sometimes, we may miss to update in all the places would create problem in our code.  In order to avoid this short coming, we use macros.

#define SIZE 20  // SIZE - macro name and 20 is its value
char first_name[SIZE];
char last_name[SIZE];
char course[SIZE];
char school[SIZE];

Now, if user wants to change the array size to 30, then he needs to change the value of macro (SIZE) alone as shown below.

#define SIZE 30             // changed the value of macro
char first_name[SIZE];
char last_name[SIZE];
char course[SIZE];
char school[SIZE];

Now, the size of all the above arrays has been increased to 30.


#define directive C example:

  #include <stdio.h>
  #include <string.h>
  #define SIZE 20

  int main() {
        char first_name[SIZE], last_name[SIZE];
        char course[SIZE], school[SIZE];
        strcpy(first_name, "Will");
        strcpy(last_name, " Smith");
        strcpy(course, "7th Grade");
        strcpy(school, "Vidya vikas");
        printf("Name: %s%s\n", first_name, last_name);
        printf("Course: %s\n", course);
        printf("School: %s\n", school);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc define.c
  jp@jp-VirtualBox:~/$ ./a.out
  Name: Will Smith
  Course: 7th Grade
  School: Vidya vikas


If user wants to change the size of all array variables to 30(elements), then its enough to change the value of macro SIZE alone.


No comments:

Post a Comment