This blog is under construction

Sunday 3 June 2012

#pragma directive in C

This directive provides some additional information to the compiler and it is also used to turn on or off certain special features.  For example, #pragma startup and #pragma exit were used to call specific functions during program entry (before main()) and exit(after main()) correspondingly.


Example C program to illustrate #pragma startup and #pragma exit:

  #include <stdio.h>
  void in() {
        printf("#pragma start in\n");
        printf("Inside in\n");
  }

  void out(){
        printf("#pragma exit out\n");
        printf("Inside out()\n");
  }

  #pragma startup in
  #pragma exit out

  int main() {
        printf("I am inside main function\n");
        printf("Going out of main()\n");
        return 0;
  }

  Output:
  #pragma start in
  Inside in
  I am inside main function
  Going out of main()
  #pragma exit out
  Inside out()


#pragma warn directive can be used to suppress specific warning as follows.
#pragma warn -rvl:
          suppresses warnings related to return values
#pragma warn -par:
          suppresses warnings related to parameters like unused parameters.
#pragma warn -rch:
          suppress warning related to unreachable codes.


Example C program to illustrate #pragma warn:

  #include <stdio.h>
  #pragma warn -rvl
  #pragma warn -par
  #pragma warn -rch

  int retval() {
        printf("missing to return value\n");
  }

  int unused_para(int a) {
        printf("I m not using my parameter value\n");
        return 0;
  }

  int unreachable_code() {
        printf("have some code after return statment\n");
        return 0;
        printf("Code after return statement\n");
        printf("Unreachable code\n");
  }

  int main() {
        retval();
        unused_para(8);
        unreachable_code();
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pragmawarn.c
  jp@jp-VirtualBox:~/cpgms/$ ./a.out
  missing to return value
  I m not using my parameter value
  have some code after return statment

If we check the above output, there won't be any warning messages.  This is due to the usage of #pragma warn.  If we remove those three pragma directives in our program, we will get warnings for unreachable code, unused parameters etc.


2 comments:

  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