C Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C Preprocessor

C Preprocessor

shape Description

Any C-program undergoes a pre-compilation process i.e before the program is compiled, there will be a process to check the program.This process is done by the C Preprocessor. Preprocessor commands are called as Directives. Directives start with # symbol. Basically, there are 4 Preprocessor directives in C-compiler.

File Inclusion Directive

shape Description

The files declared in header files can be used in the main program if once declared. The file which consists of macro definitions and C-function declarations is called as header file. These can be described more clearly in the lesson Header Files.

Macro Substitution Directive

shape Description

The #define is a macro, used to denote the constant values and they can be of any data types. Eg: #define letter 'A' Suppose if there is #define max(a,b) in the program, it appears as #define max(a>b ? a:b) after the pre-process commands are compiled.

shape Example

[c] #include<stdio.h> #define length 10 void main() { printf("value of length is: %d \n", length ); }[/c] Output: [c]value of length is: 10[/c]

Conditional Directives

shape Description

According to the condition, a set of commands can be involved or removed in the program.

shape Examples

Below is the example for if,else and endif. [c]#include<stdio.h> #define splessons 10 int main() { #if (splessons==100) printf("if is included in the source code\n"); #else printf("else is included in the source code\n"); #endif return 0; }[/c] Output: [c] else is included in the source code [/c] Example for ifdef,else,endif [c] #include<stdio.h> #define splessons 100 int main() { #ifdef splessons printf("splessons is defined.It can be added in the C file\n"); #else printf("splessons is not defined\n"); #endif return 0; }[/c] Output: [c] splessons is defined.It can be added in the C file [/c] undef is used to un-define the existing macro variable. [c] #include<stdio.h> #define height 100 void main() { printf("First defined value for height: %d\n",height); #undef length #define length 20 printf("length after undef and redefine:%d",length); }[/c] Output: [c] First defined value for height: 100 length after undef and redefine:20[/c]

Other Directives

shape Description

#pragma directive

It will allow a directive to be defined and the effects are defined by implementation. If pragma is ignored,if it is not supported.

#error directive

It halts the compilation and returns the specified error message.

#line directive

Current line number is allowed by this directive and the apparent name of the current sourcecode filename to be changed.

Summary

shape Key Points

  • Pre-processor performs pre-compilation.
  • Commands used in preprocessor are called preprocessor directives.
  • Macros, conditional directives and file inclusion directives are pre-processor directives.