Monday, July 27, 2009

Does #ifndef, #define etc mean?

I've been programming with c++ for awhile (self taught) and I was wondering...does #ifndef,#define,#endif mean respectively...


if not defined,then define, and end?





I know it's a dumb question...I just wanted to be sure...


I usually don't write programs with more than the main file.

Does #ifndef, #define etc mean?
Those are the preprocessor directives. You have to use them like macros or any other headerfiles etc.





If you write the program with a macro it might reduce the lines of code. so that reusability takes place. Header files are always used like namespaces or any other directives.
Reply:#if, #ifdef, #ifndef, #else,


#elif, and #endif (directives)


-----------------------------------


Conditional compilation directives





Syntax:


þ #if %26lt;constant-expression%26gt;


#else


#endif





þ #if %26lt;constant-expression%26gt;


#elif %26lt;constant-expression%26gt;


#endif





The compiler only compiles the lines that follow the #if directive when


%26lt;constant expression%26gt; evaluates to non-zero.





Otherwise, the compiler skips the lines that follow until it encounters the


matching #else or #endif.





If the expression evaluates to false and there is a matching #else, the


lines between the #else and the #endif are compiled.





#if directives can be nested, but matching #else and #endif directives must


be in the same file as the #if.





#if ... #elif ... #endif


-----------------------------


#elif is like #else except the else block is only compiled if the expression


after #elif is non-zero.








Alternate forms (#ifdef and #ifndef)


--------------------------------------...





The alternate form





#ifdef %26lt;identifier%26gt;





evaluates to 1 if the symbol specified by %26lt;identifier%26gt; has been previously


defined with a #define directive.





The alternate form





#ifndef %26lt;identifier%26gt;





evaluates to 1 if the symbol specified by %26lt;identifier%26gt; has not been defined.





Example 1:


#if defined(NEARPOINTERS)


space = farcoreleft();


#elif defined(FARPOINTERS)


space = coreleft();


#else


#error Unsupported memory model


#endif





Example 2:


#ifdef DEBUG


printf("Total space %d\n", space);


#endif





Example 3:


#ifndef Quiet


PrintDiagnostics();


#endif
Reply:I did not know them myself for a while too; they are preprocessor directives not part of C/C++, those directives are for the compilers.





Those directives are meant to alter programming flow and thus produce binary codes that are suitable for whatever they were meant to work towards to at the moment, all those alterations are very basic but useful nonetheless.


No comments:

Post a Comment