Thursday, July 9, 2009

What is the diffference between a 'macro' and '#define' while programming in C?

though the work of both 'macro' and ' #define' are same why do we use them as different while programming,

What is the diffference between a 'macro' and '#define' while programming in C?
The '#define' preprocessor statement works the same way, regardless of intent of the programmer. That is why macros must be handled carefully. The preprocessor simply replaces the symbols with the replacements, no matter what the results. Consider this case of the code below.





#include %26lt;stdio.h%26gt;





/*Constant*/


#define ADD +


/*Macro - Takes parameters*/


#define ADD2(x) (x+2)


/* Stringized*/


#define PRINT(token) printf(#token " is %d\n", token)





int main(void)


{


int Res;


float Tes = 12.45;


char Oops = 'D';





Res = 24 ADD 30;


puts("24 ADD 30\n");


PRINT(Res);


Res = ADD2(Res);


PRINT(Res);


Tes = ADD2(Tes);


printf("Tes is %f\n", Tes);


Oops = ADD2(Oops);


printf("\nAs numeric, %d\nAs character, %c\n", Oops, Oops);


system("PAUSE");


return 0;


}








This program uses a constant ADD and a macro ADD2 for a quicky demo. The problem isn't that the macro will not function in this case, but that it will. The definition could've been even more confusing and the names may have collided in a larger program. There is never any type checking of parameters in a macro. So when it is called with a character, it adds the 2 to its value just as if it was an integer or float. Would this always be an intended result, if say, a function was defined called ADD2 that estends an array of characters by 2 and returns a pointer? Okay, that may be hard to imagine, but stranger things have happen. Back to the original question. A defined constant does simple replacements as ADD does here, not always as one might think, but a good practice for constants used in multiple places. Okay, a macro takes parameter(s) just like a function and evaluates the statement that it places them in. The third trick is the ## and # used to paste and stringizing or #.





If this doesn't get the point across, try the URLs below.
Reply:its a gr8 gesture for answering such a quetion with such a calm and devotion!!! Report It


secret garden

No comments:

Post a Comment