0% found this document useful (0 votes)
70 views18 pages

Unit 2 Preprocessor

The document discusses C preprocessor directives and bitwise operators. It provides 11 directives including #define, #include, #undef, #ifdef, #ifndef, #if, #else, #elif, #endif, #error, and #pragma. It explains how these directives work and provides examples of using each one. Various bitwise operators like MAX_ARRAY_LENGTH, FILE_SIZE, and NOINPUT are demonstrated. Predefined macros like __DATE__, __TIME__, __FILE__, and __LINE__ are also described.

Uploaded by

richa.vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views18 pages

Unit 2 Preprocessor

The document discusses C preprocessor directives and bitwise operators. It provides 11 directives including #define, #include, #undef, #ifdef, #ifndef, #if, #else, #elif, #endif, #error, and #pragma. It explains how these directives work and provides examples of using each one. Various bitwise operators like MAX_ARRAY_LENGTH, FILE_SIZE, and NOINPUT are demonstrated. Predefined macros like __DATE__, __TIME__, __FILE__, and __LINE__ are also described.

Uploaded by

richa.vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Introduction to C Preprocessor Bitwise Operators

C 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.

All preprocessor directives starts with hash # symbol.

Sr.No. Directive & Description

1 #define

Substitutes a preprocessor macro.

2 #include

Inserts a particular header from another file.

3 #undef

Undefines a preprocessor macro.

4 #ifdef

Returns true if this macro is defined.

5 #ifndef

Returns true if this macro is not defined.


6 #if

Tests if a compile time condition is true.

7 #else

The alternative for #if.

8 #elif

#else and #if in one statement.

9 #endif

Ends preprocessor conditional.

10 #error

Prints error message on stderr.

11 #pragma

Issues special commands to the compiler, using a standardized method.

Preprocessors Examples
Analyze the following examples to understand various directives.

#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.

#include <stdio.h>

#include "myheader.h"

These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.hfrom the local directory and add
the content to the current source file.

#undef FILE_SIZE

#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE
#define MESSAGE "You wish!"

#endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG

/* Your debugging statements here */

#endif

It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you
pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define
DEBUG, so you can turn debugging on and off on the fly during compilation.
C 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:

1. Object-like Macros
2. Function-like 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:

1. #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:

1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming,
the predefined macros should not be directly modified.

Sr.No. Macro & Description


1 __DATE__

The current date as a character literal in "MMM DD YYYY" format.

2 __TIME__

The current time as a character literal in "HH:MM:SS" format.

3 __FILE__

This contains the current filename as a string literal.

4 __LINE__

This contains the current line number as a decimal constant.

5 __STDC__

Defined as 1 when the compiler complies with the ANSI standard.

#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("ANSI :%d\n", __STDC__ );

C #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.

1. #include <filename>
2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files
are held. In UNIX, it is \usr\include directory.

The #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.

1. #include<stdio.h>
2. int main(){
3. printf("Hello C");
4. return 0;
5. }

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is
treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in
case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.

Syntax:

1. #define token value

Let's see an example of #define to define a constant.

1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }

Output:
3.140000
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

1. #undef token

Let's see a simple example to define and undefine a constant.

1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you
can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being
undefined, it was used by square variable.

1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }

Output:

225
C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.

Syntax:

1. #ifdef MACRO
2. //code
3. #endif

Syntax with #else:

1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }

Output:

Enter a:5
Value of a: 5
C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes
the code otherwise #else code is executed, if present.

Syntax:

#ifndef MACRO
//code
#endif

Syntax with #else:

#ifndef MACRO
//successful code
#else
//else code
#endif

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

#include <stdio.h>
#include <conio.h>
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}

Output:

Value of a: 2
C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

#if expression
//code
#endif

Syntax with #else:

#if expression
//if code
#else
//else code
#endif
Syntax with #elif and #else:

#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif

C #if example

Let's see a simple example to use #if preprocessor directive.

#include <stdio.h>
#include <conio.h>
#define NUMBER 0
void main() {
#if (NUMBER==0)
printf("Value of Number is: %d",NUMBER);
#endif
getch();
}

Output:

Value of Number is: 0

Let's see another example to understand the #if directive clearly.

#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
clrscr();
#if (NUMBER==0)
printf("1 Value of Number is: %d",NUMBER);
#endif

#if (NUMBER==1)
printf("2 Value of Number is: %d",NUMBER);
#endif
getch();
}

Output:
2 Value of Number is: 1
C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

#if expression
//if code
#else
//else code
#endif

Syntax with #elif:

#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif

C #else example

Let's see a simple example to use #else preprocessor directive.

#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}

Output:

Value of Number is non-zero


C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
C #error example

Let's see a simple example to use #error preprocessor directive.

#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

#include<stdio.h>
#include<math.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif

Output:

2.645751

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler.
The #pragma directive is used by the compiler to offer machine or operating-system feature.
Syntax: #pragma token

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

1. #pragma argsused
2. #pragma exit
3. #pragma hdrfile
4. #pragma hdrstop
5. #pragma inline
6. #pragma option
7. #pragma saveregs
8. #pragma startup
9. #pragma warn

Let's see a simple example to use #pragma preprocessor directive.

#include<stdio.h>
#include<conio.h>
void func() ;
#pragma startup func
#pragma exit func
void main(){
printf("\nI am in main");
getch();
}
void func(){
printf("\nI am in func");
getch();
}

Output:

I am in func
I am in main
I am in func

Bitwise Operators in C
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (A & B) =
12, i.e.,
both operands. 0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) =


61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) =


but not both. 49, i.e.,
0011 0001

~ (~A ) = -61,
i.e,. 1100
Binary Ones Complement Operator is unary and has the effect
0011 in 2's
of 'flipping' bits.
complement
form.

<< Binary Left Shift Operator. The left operands value is moved A << 2 =
left by the number of bits specified by the right operand. 240 i.e.,
1111 0000

>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15
right by the number of bits specified by the right operand. i.e., 0000
1111

Example
Try the following example to understand all the bitwise operators available in C −

#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13;/* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

C Bitwise Operator Masking

Bitwise Operations and Masking in C Programming

We have learnt different Bitwise Operation Techniques, in this chapter we are going to
learn the masking technique to set particular bit on or off.
[box]Masking is the process or operation to set bit on to off or off to on in a byte,nibble
or word.[/box]

1. Mask means to block.

2. Masking is the process by which ,only required data is retained and the rest is

masked (blocked)

3. Masking can be done using Bitwise Operators

4. Most Commonly Used Bitwise Operator is AND(&)

A. Masking bits to 1 :

1. In this case we need to retain the particular data.

2. Bitwise OR Operator is used for masking bits to 1

Truth table for Bitwise OR :

We can summarize above table as –


Bit 1 Bit 2 Bitwise OR

1 Y 1

0 Y Y

Masking Bits to 1

10011101 10010101
00001000 00001000 OR
-----------------------------
10011101 10011101

B. Masking bits to 0 :

In this case we need to remove data by masking it to 0

Truth table for Bitwise AND :

Bit 1 Bit 2 Bitwise AND

0 0 0

1 1 1

0 1 0

1 0 0

We can summarize above table as –

Bit 1 Bit 2 Bitwise AND

1 Y 1

0 Y Y
Masking or Hiding the Last 4 LSB Bits :

Process of Masking : We want Last 4 LSB Bits , So Mask it with (0000 0000 0000 1111)

Num 1 : 1000 0001 1110 1011


& : 0000 0000 0000 1111
--------------------------------
Result : 0000 0000 0000 1011

We get Result as :-

Num 1 : 0000 0000 0000 1011 // First 12 bits are Masked

Important Question
1. What is define directive?
2.What are bit-wise operators? Explain shift operator by giving examples.

3. What are C preprocessors? Explain the role of conditional compilation.

4. What are preprocessor directive? Why do we need them ? Explain various preprocessor
directives.

5. ‘C’ compiler supports many pre-processor commands. Write their name only.

6. What do you know about bit-wise operation? Explain about some bit wise operator by
providing the examples for each.

7. Distinguish between #ifdef and #if directive.

8. What is ‘union’ in C? Explain its usage.

You might also like