Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros. The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.
What is Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
The function-like macro looks like function call. For example:
#define MIN(x, y) ((x) < (y)? (x): (y))
Here, MIN is the macro name.
Predefined Macros
ANSI C defines many predefined macros that can be used in c program.No. | Macro | Description |
---|---|---|
1 | _DATE_ | represents current date in "MMM DD YYYY" format. |
2 | _TIME_ | represents current time in "HH:MM:SS" format. |
3 | _FILE_ | represents current file name. |
4 | _LINE_ | represents current line number. |
5 | _STDC_ | It is defined as 1 when compiler complies with the ANSI standard. |
predefined macros example
simple.c#include <stdio.h> main() { printf("File :%s\n", __FILE__ ); printf("Date :%s\n", __DATE__ ); printf("Time :%s\n", __TIME__ ); printf("Line :%d\n", __LINE__ ); printf("STDC :%d\n", __STDC__ ); } Output: File :simple.c Date :AUG 10 2017 Time :11:10:40 Line :6 STDC :1
#include
The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error. By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.
#include <filename>
tells the compiler to look for the directory where system header files are held. In UNIX, it is \user\include directory.#include "filename"
tells the compiler to look in the current directory from where program is running#include directive example
Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.#include <stdio.h> main() { printf("Hello C program"); } Output: Hello C program