Friday, March 20, 2009

Preprocessing in C

C's preprocessor provides a facility for defining constant and substitution, which are commonly called macros.
  • #include
The include directive tells the compiler to include all the contents of a specified file in the source file before giving the source file for compiling.

eg: #define TRUE 1
  • #undef
Nullify the effect of define directive.
eg: #undef TRUE
#define TRUE correct

Angle brackets Searches in the default directories of include files.

Quotes specifies search in current directory.
  • #ifdef
ifdef is used to make a substitution depending on whether a certain identifier is defined. If defined returns true else false.

e.g: #ifdef TRUE
#define FALSE 0
Note: we can easily add multiple macros in between the two macros.
  • #ifndef
eg: #ifndef FALSE
#define WRONG 0
  • #if
#if allows you to define more generalized conditions. Multiple conditions, which are connected by relational operators such as AND(&&), OR(||), are allowed.
  • #error
Used to display error message by preprocessor.

#if !define FALSE
#error "Specify FALSE condition"
  • #line
Mainly used for debugging purpose.
eg: #line100 indicates it is in line 100

C has provided two special identifiers: __FILE__ and __LINE__, which indicate the file name of the source file and the current line number, respectively.

Macros allow replacement of the identifier by using a statement or expression.
eg: #define CUBE(x) x*x*x

No comments:

Post a Comment