This blog is under construction

Wednesday, 23 May 2012

#define vs const

Earlier, #define is the only way to define constants.  Later const came in, which is also used to define constants.  Most of the programmers prefer to use const over #define for the following reasons
  1. Syntax check will be done for const but not for #define. The #define directive is not checked for syntax errors until the error macro is used in code block.
  2. #define can only define simple constant.  But, const can define complex constants as shown below.
struct student {
         char name[100];
         int age;
         float percentage;
};

const struct student obj = {"Victor", 20, 89};

Consider the following example,

  #include <stdio.h>
  #define SUM 10+
  int main() {
        int a;
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Hello world


In the above C program, we have a syntax error in macro definition(#define SUM 10+). But, it wasn't reported to us since we haven't used it anywhere in our code.  Let us see what happen if we use the same macro inside the code block

  #include <stdio.h>
  #define SUM 10+
  int main() {
        int a = SUM;  // SUM is the macro with syntax error
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pgm.c 
  pgm.c: In function ‘main’:
  pgm.c:4: error: expected expression before ‘;’ token


In the above program, the definition for macro SUM has syntax error and the same is assigned to integer variable a.  During preprocessing 10+ would be assigned to variable a, compiler detects the same as error during compilation process.

Let us see how const behaves when there is some syntax error.


  #include <stdio.h>
  int main() {
        const int a = 10+; 
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pgm.c 
  pgm.c: In function ‘main’:
  pgm.c:4: error: expected expression before ‘;’ token


Syntax error with const is reported during compilation itself.


1 comment:

  1. Dell Laptop Repair Center in Noida is no.1 service center which provides door to door services in or its nearby areas. We have expert, technicians who can repair your laptop at your home. . Call us: 9891868324

    ReplyDelete