Wednesday, 28 January 2015

Preprocessor Statements #ifdef, #else, #endif


Consider the following C program



#define FIRST
int main()
{
    int x, y, z;
#ifdef FIRST
    x=2; y=6; z=4;
#else
    printf("Enter x:");
    scanf("%d", &x);
    printf("Enter y:");
    scanf("%d", &y);
    printf("Enter z:");
    scanf("%d", &z);
#endif

    printf(“x:%d\ny:%d\nz:%d”);
    return 0;
}


Note that if FIRST is defined using the #define, the values of x, y and z are hardcoded to values of 2, 6 and 4. When FIRST is defined, all that is passed to the compiler is the code between the #ifdef and the #else. The code between the #else and the #endif is not seen by the compiler and is simply ignored. It is as if it were all a comment.
Once you have your routine working, and desire to insert the printf and scanfs, all that is required is to go back and delete the the #define FIRST. Now, the compiler now ignores the following statements:

a=2; b=6; c=4;
but does see the printf and scanfs.


Quite often you will have code which doesn't work, but you really don't want to throw it away. I see many students doing this;
/*
unwanted code
*/
And this is acceptable. Of course a problem arises is you have a comment in the unwanted code.
Thus, it is better to do this

#ifdef OLD
     unwanted code
#endif 


No comments:

Post a Comment