0% found this document useful (0 votes)
46 views22 pages

CP Unit-4 R19

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

CP Unit-4 R19

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

PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Pointers
Pointers
Generally computer uses memory for storing instruction and values of the variables which we are
using in the program, but the pointers have memory address as their values. The memory address
is the location where program instructions and data are stored; pointers can be used to access and
manipulate data stored in the memory.
Example : int sno=39; above statement instructs the system to specify a location for the integer
variable 'sno' and put the value 39 in that location. Assume that the system has chosen the
address location 65542 for sno this may be represented as
sno
39
65542
sno - Variable
39 - Value
65542 - Address

Pointer Concept:
"A pointer is a variable, it may contain the memory address of another variable." Pointer can
have any name that is legal for other variable. It is declared in the same manner like other
variables. It is always denoted by '*' operator.
Pointer Declaration:
Pointer is a variable that contain the address of another variable. Like normal variable declared in
'C' pointers can also be declared.
Syntax data-type *pointer-name;
Description data-type Specifies the type of data to which the pointer points.
Pointer-name Specifies the name of the pointer. (It must preceded with an (*) asterisk.
Example: int *a; *a mean 'a' contains the address of variable, which is integer variable.
char *b; *b mean 'b' contain the address of variable, which is character variable.
float *c; *c means 'c' contain the address of variable, which is float variable.

Accessing variable through pointer


Once the pointer is declared and assigned to the address of another variable, the variable can be
accessed through its pointers. This is done by using another unary operator * (asterisk), usually
known as the indirection operator. Another name for the indirection operator is the dereferencing
operator.

RIET,CSE Page 1
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Example : /* Program to accessing variable through pointer */


#include<stdio.h>
main ( )
{
int a=22;
int *a; a=&a;
printf ("\n Value of a=%d", *a); //22
printf ("\n Address of a=%u", &a); //4000
printf ("\n Value at address %u=%d", &a, *(&a)); //4000=22
}

Pointer Expressions & Pointer Arithmetic( Address Arithmetic):


We can perform arithmetic operations on pointer variable just as you can a numeric value. As we
know that, a pointer in C is a variable which is used to store the memory address which is a
numeric value. The arithmetic operations on pointer variable effects the memory address pointed
by pointer.
Valid Pointer Arithmetic Operations
 Adding a number to pointer.
 Subtracting a number form a pointer.
 Incrementing a pointer.
 Decrementing a pointer.
 Subtracting two pointers.
 Comparison on two pointers.
Invalid Pointer Arithmetic Operations
 Addition of two pointers.
 Division of two pointers.
 Multiplication of two pointers.
Incrementing a Pointer
Let ptr be an integer pointer which points to the memory location 5000 and size of an integer
variable is 32-bit(4 bytes). Now, when we increment pointer ptr.
ptr++;
it will point to memory location 5004 because it will jump to the next integer location which is 4
bytes next to the current location. Incrementing a pointer is not same as incrementing an integer

RIET,CSE Page 2
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

value. On incrementing, a pointer will point to the memory location after skipping N bytes,
where N is the size of the data type(in this case it is 4).
ptr++ is equivalent to ptr + (sizeof(pointer_data_type)).
"Incrementing a pointer increases its value by the number of bytes of its data type"
A character(1 bytes) pointer on increment jumps 1 bytes.
An integer(4 bytes) pointer on increment jumps 4 bytes.
This is a very important feature of pointer arithmetic operations which we will use in array
traversal using pointers.
Decrementing a Pointer
Similarly, Decrementing a pointer will decrease its value by the number of bytes of its data type.
Hence, after
ptr--;
ptr will point to 4996.
ptr--; is equivalent to ptr - (sizeof(pointer_data_type)).
Adding Numbers to Pointers
Adding a number N to a pointer leads the pointer to a new location after skipping N times size of
data type.
ptr + N = ptr + (N * sizeof(pointer_data_ype))
For example, Let ptr be a 4-byte integer pointer, initially pointing to location 5000.
Then ptr + 5 = 5000 + 4*5 = 5020. Pointer ptr will now point at memory address 5020.
Subtracting Numbers from Pointers
Subtracting a number N from a pointers is similar to adding a number except in Subtraction the
new location will be before current location by N times size of data type.
ptr - N = ptr - (N * sizeof(pointer_data_ype))
For example, Let ptr be a 6-byte double pointer, initially pointing to location 5000.
Then ptr - 3 = 5000 - 6*3 = 4982. Pointer ptr will now point at memory address 4982.
Subtracting Pointers
We can take difference between two pointer which returns the number of bytes between the
address pointed by both the pointers.
For example, if a pointer 'ptr1' points at memory location 10000 and pointer 'ptr' points at
memory location 10008, the result of ptr2 - ptr1 is 8.

RIET,CSE Page 3
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Dangling pointer and Dangling memory:

If any pointer is pointing the memory address of any variable but after some variable has deleted
from that memory location while pointer is still pointing such memory location. Such pointer is
known as dangling pointer and such memory is known as dangling memory. In short pointer
pointing to non-existing memory location is called dangling pointer.

Initially: Later:

Null Pointer:
A pointer is said to be a null pointer when its right value is 0. A null pointer can never point to a
valid data. For checking a pointer, if it is assigned to 0, then it is a null pointer and is not valid.
Example : int *a;
int *b;
b=a=0;
Hence b and a become null pointers after the integer value of 0 is assigned to them.

Pointer to Pointer: Pointer is a variable that contains the address of another variable. Similarly
another pointer variable can store the address of this pointer variable. So we can say, this is a
pointer to pointer variable.

/* Program using pointer to pointer */


#include<stdio.h>
main ( )
{
int a=22; /* Local definitions */
int *b; /* *b is a pointer variable */
int **c; /* **c is a pointer to another pointer */
b=& a; /* '&a' is a address variable */
c=& b;
printf ("\n Value of a is %d", a); //22
printf ("\n Value of a is %d", *(&a)); //22
printf ("\n Value of a is %d", *b); //22
RIET,CSE Page 4
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

printf ("\n Value of a is %d", **c); //22


printf ("\n Value of b and address of a =%u", b);//2000
printf ("\n Value of c and address of b =%u", c);//4000
printf ("\n Address of a=%u", &a); //2000
printf ("\n Address of b=%u", &b); //4000
printf ("\n Address of a=%u", *c); //2000
printf ("\n Address of b=%u", &b); //4000
printf ("\n Address of b=%u", c); //4000
printf ("\n Address of c=%u", &c); //6000
}

Compatibility
• Pointers have a type associated with them, such as char, int, float, etc.
• Each pointer takes on the attributes of the type to which it refers to in addition to its own
attributes.
• Compatibility types are:
a) Pointer Size Compatibility
b) Dereference Type Compatibility
c) Dereference Level Compatibility

Pointer Size Compatibility


• The size of all pointers is the same.
• Every pointer variable holds the address of one memory location in the computer.
• On the other hand, the Size of the variable that the pointer references can be different.
• The pointer also takes the attributes of the type being referenced.
Example: Prints the size of each pointer and the size of each referenced variable.
Dereference Type Compatibility
• The dereference type is the type of the variable that the pointer is referencing.
• It is invalid to assign a pointer of one type to a pointer of another type.
• A pointer to a char is only compatible with a pointer to a char.
• A pointer to an int is only compatible with a pointer to an int.
• Do not assign a pointer to a char to a pointer to an int.
• The exception to the reference type compatibility rule is the pointer to Void (A void
pointer cannot be dereferenced).

RIET,CSE Page 5
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Example:

Casting Pointers
• The problem of type incompatibility can be solved by using casting.
• An explicit assignment between incompatible pointer types is done by using a cast
operator.
• For example,
• pc=(char *)&a; /*pc is a character pointer and a is a integer pointer */
• This converts an integer pointer to a char and assigns the value to pc.

Dereference Level Compatibility


• A pointer to int is not compatible with a pointer-to-pointer to int.
• The pointer to int has a reference type of int, while a pointer-to-pointer to int has a
reference type of pointer to int
Example

RIET,CSE Page 6
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

L value and R value


L-value: “l-value” refers to memory location which identifies an object. l-value may appear as
either left hand or right hand side of an assignment operator(=). l-value often represents as
identifier.
Expressions referring to modifiable locations are called “modifiable l-values“. A modifiable l-
value cannot have an array type, an incomplete type, or a type with the const attribute. For
structures and unions to be modifiable lvalues, they must not have any members with
the const attribute. The name of the identifier denotes a storage location, while the value of the
variable is the value stored at that location.
An identifier is a modifiable lvalue if it refers to a memory location and if its type is arithmetic,
structure, union, or pointer. For example, if ptr is a pointer to a storage region, then *ptr is a
modifiable l-value that designates the storage region to which ptr points.
1.The name of the variable of any type i.e, an identifier of integral, floating, pointer, structure, or
union type.
2.A subscript ([ ]) expression that does not evaluate to an array.
3.A unary-indirection (*) expression that does not refer to an array
4.An l-value expression in parentheses.
5.A const object (a nonmodifiable l-value).
6.The result of indirection through a pointer, provided that it isn’t a function pointer.
7.The result of member access through pointer(-> or .)

int a; // declare a an object of type 'int'


a = 1; // a is an expression referring to an, // 'int' object as l-value
int b = a; // Ok, as l-value can appear on right
// Switch the operand around '=' operator
9 = a; // Compilation error: // as assignment is trying to change the value of assignment operator

R-value: r-value” refers to data value that is stored at some address in memory. A r-value is an
expression that can’t have a value assigned to it which means r-value can appear on right but not
on left hand side of an assignment operator(=).

int a = 1, b; // declare a, b an object of type 'int’


a + 1 = b; // Error, left expression is not variable(a + 1)
int *p, *q; // *p, *q are lvalue // declare pointer variable 'p', and 'q'
*p = 1; // valid l-value assignment
// below is invalid - "p + 2" is not an l-value
p + 2 = 18;
q = p + 5; // valid - "p + 5" is an r-value

RIET,CSE Page 7
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

// Below is valid - dereferencing pointer expression gives an l-value


*(p + 2) = 18;

p = &b;

int arr[20]; // arr[12] is an lvalue; equivalent to *(arr+12)


// Note: arr itself is also an lvalue

struct S { int m; };

struct S obj; // obj and obj.m are lvalues

// ptr-> is an lvalue; equivalent to (*ptr).m


// Note: ptr and *ptr are also lvalues
struct S* ptr = &obj;

Remembering the mnemonic, that lvalues can appear on the left of an assignment operator
while rvalues can appear on the right.

// declare a as int variable and


// 'p' as pointer variable
int a, *p;
p = &a; // ok, assignment of address at l-value
&a = p; // error: &a is an r-value

int x, y;

( x < y ? y : x) = 0; // It's valid because the ternary


// expression preserves the "lvalue-ness"
// of both its possible return values

RIET,CSE Page 8
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Pointer and Functions: The pointer can be used as arguments in functions. The arguments or
parameters to the function are passed in two ways.

i) Call by value
ii) Call by reference

Call By Value: The process of passing the actual value of variables is known as "call by value".
When a function is called in program, the values to the arguments in the function are taken by
the calling program; the value taken can be used inside the function. Alteration to the value is not
accepted inside the function in calling program but change is locally available in the function.
Example : /*Write a program to swap (interchange) the two given variable.*/
#include<stdio.h>
main ( )
{
int a=10, b=20;
printf ("\n Before swap a=%d,b=%d",a,b); //10, 20
void swap(a,b);
printf ("\n After the calling the swap function, a=%d,b=%d", swap(a,b); //10, 20
}
void swap(x,y)
int x,y;
{
x=x+ y;
y=x-y;
x=x-y;
printf ("In swap function x=%d,y=%d",x,y); //20, 10
}

Call By Reference: The process of calling a function using pointers to pass the addresses of
variables is known as "call by reference". A function can be declared with pointers as its
arguments. Such function is called by calling program with the address of a variable as argument
from it.
Example : /* Program to explain about call by reference */

#include<stdio.h>
main ( )
{
int a=10, b=20;

RIET,CSE Page 9
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

printf ("\n Before calling the function a&b is %d,%d",a,b); //10, 20


void change(&a,&b); /* change is a function call with parameters */
printf ("\n After calling the function a&b is %d%d", a,b); //15, 30
}

void change(x,y)
int x,y;
{
x=x + 5;
y=y + 10;
printf ("In the function changes a&b is %d,%d",*x,*y); //15, 30
}

Pointer and Arrays: Array is a collection of similar data type elements stored under common
name. When we declare an array the consecutive memory locations are located to the array of
elements. The elements of an array can be efficiently accessed by using pointers.
Example : /* Program to add the sum of number using pointer * /
#include<stdio.h>
main( )
{
int b, total;
int a[5];
int * c;
for (b=0;b<5;b++ )
{
printf ("Enter the number%d” , b+1); //10 20 30 40 50
scanf ("%d",&a[b]);
}
c=a;
for (b=0;b<5;b++ )
{
printf ("%d",* c);
total=total + * c;
c = c + 1;
}
printf ("\n Total=%d", total); //150
}

RIET,CSE Page 10
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Arrays of Pointer: The array elements can be accessed by two methods.


Standard array notation
Pointer arithmetic
Array notation is a form of relative addressing. The compiler treats the subscripts as a relative
offset from the beginning of the array. When a pointer variable is set to the start of an array and
is incremented to find the next element, absolute addressing is being implemented.

Example : /* Program to print the value and address of the element using array of pointers */
#include<stdio.h>
main( )
{
int *a[3]; /* *a[3] is a pointer variable */
int b=10, c=20, d=30, i;
a[0]=&b;
a[1]=&c;
a[2]=&d;
for (i=0; i<3; i++)
{
printf ("Address=%u",a[i]);
printf ("Value=%d",*(a[i]));
}
}

Pointer and String:


i). Character and Pointer
A character pointer is a pointer to the character. It can be declared as
char *pointer_character;
A character pointer can also be used to access character arrays and string constants, in the same
way as accessing numeric arrays using their respective pointer variable.
ii) String and pointers
A string can conveniently be represented by either using a one-dimensional character array as a
character pointer. A string constant is accessed by a pointer to its first element.
If pointer message is declared as char *pointers message;
Example: /* Program to string pointer */
# include<stdio.h>
main( )
{

RIET,CSE Page 11
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

char *ptr, str[]=”vahini”;


int i, len
ptr=str;
len=strlen(str);
for(i=0;i<len;i++)
printf(i=0;i<len;i++)
printf(“%c”, *(ptr+i));
getch();
}
Dynamic Memory Allocation: Dynamic memory allocation means, a program can obtain its
memory while it is running. It allows us to allocate additional memory space or to release
unwanted space at the time of program execution (runtime).
Pointers support the dynamic memory allocation in 'C' language. The 'C' language provides four
library functions known as 'Memory Management Functions' which can be used for allocating
and releasing memory during execution.
Dynamic memory allocation functions

FUNCTION MEANING
malloc() Used to allocate blocks of memory in required size of bytes.
free() Used to release previously allocated memory space.
calloc() Used to allocate memory space for an array of elements
realloc() Used to modify the size of the previously allocated memory space.

malloc() function: The malloc() function is used to allocate block of memory (i.e.) it allocates a
block of memory of specified size and return a pointer of type void. It takes the following form-
Ptr=(data_type*)malloc(byte_size);
int *p;
p=(int *)malloc(5*(sizeof (int));

1024 1026 1028 1030 1032


P

1024 >

calloc()function: The calloc() function is used for allocating memory space during the program
execution for derived data types such as arrays, structures etc. It takes the following form-

RIET,CSE Page 12
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Ptr=(data_type*)calloc(n, byte_size);

int *p;
p=(int *)calloc(10*(sizeof (int));
free(p);
P 1024 1026

1024 > 0 0 .................................

free() function: The free() function is used to release the previously allocated memory space
using malloc() or calloc() i.e., it is the opposite of malloc() function. It takes the following form-
Syntax void free(void *p);
int *p;
p=(int *)malloc(5*(sizeof (int));
free(p);

realloc() function: It is necessary to alter the previously allocated memory. i.e.,to add additional
memory or to reduce as and when required.
For above purposes, the realloc() function is very useful and this process is called reallocation of
memory.
Before using this statement, the user must allocate some memory previously by using the
malloc() function.
new_ptr=(data_type*)realloc(old_ptr, new_size);

int *p;
p=(int *)malloc(10* sizeof(int));
p=(int *)realloc(p,10));

Malloc realloc
#include<stdio.h> #include<stdio.h>
#include<malloc.h> #include<malloc.h>
void main() #include<string.h>
{ void main()
int *ptr, n, i; {
printf("ENter no. of elements"); char *name;
scanf("%d", &n); //4 name=(char *)malloc(12,sizeof(char));
iptr=(int *) malloc(n*sizeof(int)); strcpy(name, "VaniCollege");
printf(Enter %d elements\n" n); printf("Name %s at address %d", name,name);
for(i=0;i<n;i++) name=(char *)realloc(name, 15*sizeof(char));
scanf("%d",iptr+1); //10,20.30.40 strcpy(name, "VahiniCollege");
printf("The list of the elements\n"); printf("Name %s is at address %d\n", name, name);
for(i=0;i<n;i++) free(name);
printf("%d\n", &(iptr+1)); getch();
free(iptr); }
}

RIET,CSE Page 13
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Operations on Operators: The arithmetic operations on pointers such as postfix, prefix,


increment and decrement operation can be performed on the pointer. It means addition or
subtraction by 1 with these variable, but here the postfix, prefix, increment, decrement means
addition or subtraction of bytes that pointer data type hold with the value that the pointer variable
contains.
Example : /* Program to find the sum of two numbers using pointers */
#include<stdio.h>
#include<conio.h>
main( )
{
int a, b, c;
int *a,*b; /* *a,*b is a pointer variables */
printf ("\n Enter two integer value");
scanf ("%d %d", &a, &b);
*a=&a;
*b=&b;
c=*a+ *b;
printf ("\n Sum of two integer is=%d", c);
}

RIET,CSE Page 14
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

PRE PROCESSOR DIRECTIVES

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform programmer defined programs before actual compilation takes place. It is called a
macro processor because it allows the user to define macros, which are short abbreviations for
longer constructs.

To sum up, preprocessing directives occurs before program compilation. So, it can be also be
referred to as pre compiled fragments of code.
Some possible actions
1. File Inclusion
2. Macros
3. Conditional Compilation
4. Other directives
.
All preprocessor directives has begin with the # operator.

1. File inclusion
 The file inclusion uses the #include.
Syntax:
#include filename
 The content that is included in the filename will be replaced at the point where the
directive is written.
 By using the file inclusive directive, we can include the header files in the programs.
 Macros, function declarations, declaration of the external variables can all be combined
in the header file instead of repeating them in each of the program.
 The stdio.h header file contains the function declarations and all the information
regarding the input and output.
There are two ways of the file inclusion statement:
i) #include “file-name”
ii) #include <file-name>
 If the first way is used, the file and then the filename in the current working directory and
the specified list of directories would be searched.
 If the second way, is used the file and then the filename in the specified list of directories
would be searched.
2.Macro Definition or #define Preprocessor Directive
The #define preprocessor directive for symbolic constants :
• Used to create symbolic constants with the format
#define identifier replacement-text
• Enables the programmer to create a name for the constant and use that name throughout
the program, making the program self-documenting

RIET,CSE Page 15
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

• The constant can be modified by another #define directive


• Exemplified by
#define PI 3.14159265358
replaces all subsequent occurrences of the symbolic constant PI with the numeric
constant 3.14159265358
• Be careful not to put a semicolon at the end of the statement
• The statement terminates with the end of line but can be extended on to another line by
using a backslash character (’\’)
Example:
#include <stdio.h>
#define PI 3.1415
main()
{
printf("%f",PI);
} O/P: 3.14000

The #define preprocessor directive for macros:


• A macro is a segment of code which is replaced by the value of macro.
or
A macro is an operation defined in a #define preprocessor directive with or without
parameters
• A macro without parameters is processed just like a symbolic constant
• A macro with parameters is expanded with its parameter list
• Example: macro.c
• However, it is preferable to define the above macro as
#define max(x,y) ( (x) > (y) ? (x) : (y) )
as this macro can now be used in more complicated contexts such as
a = 1 + max ( b = c + 2, d );
• Not good for efficiency but gives correct result
• A \ can be used to extend the #define to the next line so that the definition can be
arbitrarily long
Example:

#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
O/P: Minimum between 10 and 20 is: 1
RIET,CSE Page 16
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Some of the predefined macros which are readily available are as follows:

Macro Description

___LINE___ It contains a current line number as a decimal constant.

___FILE___ It contains the current filename as a string literal.

___DATE___ It shows the current date as a character literal in the “MMM DD


YYYY” format.

___TIME___ It shows the current time as a character literal in “HH:MM:SS”


format.

___STDC___ It is defined as 1 when the compiler complies with the ANSI


standard.

___TIMESTAMP___ It is a sing literal in the form of “DDD MM YYYY Date


HH:MM:SS”. It is used to specify the date and time of the last
modification of the current source file.

3.Conditional Compilation:

Conditional Compilation directives are type of directives which helps to compile a specific
portion of the program or to skip compilation of some specific part of the program based on
some conditions.

The directives are:

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

#ifdef MACRO
//code
#endif

Syntax with #else:

#ifdef MACRO
//successful code

RIET,CSE Page 17
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

#else
//else code
#endif
Example:

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

But, if you don't define NOINPUT, it will ask user to enter a number. So output of program is
Enter a:5
Value of a: 5

#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

RIET,CSE Page 18
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

Example:

#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. Then output is
Value of a: 2

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

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

#elif : The preprocessor will include the C source code that follows the #elif statement
when the condition of the preceding #if, #ifdef or #ifndef directive evaluates to false and
the #elif condition evaluates to true.

#endif: The #endif directive closes off the following directives: #if, #ifdef, or #ifndef. When
the #endif directive is encountered

Syntax:

#if expression
//if code
#elif expression

RIET,CSE Page 19
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

//elif code
#else
//else code
#endif
Example:

#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

4 Other directives:

Apart from the above directives there are some more directives which are not commonly used.
These are

1)Line control ( #line ): Whenever we compile a program, there are chances of occurrence of
some error in the program. Whenever compiler identifies error in the program it provides us with
the filename in which error is found along with the list of lines and with the exact line numbers
where the error is. This makes easy for us to find and rectify error.
However we can control what information should the compiler provide during errors in
compilation using the #line directive.
Syntax:
#line number "filename"
number – line number that will be assigned to the next code line. The line
numbers of successive lines will be increased one by one from this point on.
“filename” – optional parameter that allows to redefine the file name that will be
shown.

RIET,CSE Page 20
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

2)Error directive ( #error ): This directive aborts the compilation process when it is found in
the program during compilation and produces an error which is optional and can be specified as a
parameter.
Syntax:
#error optional_error
Here, optional_error is any error specified by the user which will be shown when this
derective is found in the program.

3)Undef directive(#undef):
This directive undefines or removes a macro name previously created with #define.
Syntax:
#undef macro_name
Here #undef is followed by macro name that has to be undefined.
Similar to definition, undefinition also occurs at the specific point in the source file, and it
applies starting from that point.
Therefore #undef directive removes the current definition of macro and all subsequent
occurrences of macro name are ignored by the preprocessor.
4) Pragma Directive(#pragma):

This directive is a special purpose directive and is used to turn on or off some features. This type
of directives are compiler-specific i.e., they vary from compiler to compiler. Some of the
#pragma directives are discussed below:

1. #pragma startup and #pragma exit: These directives helps us to specify the functions
that are needed to run before program startup( before the control passes to main()) and
just before program exit (just before the control returns from main()).

Example:

#include<stdio.h>
#include<conio.h>

void func() ;

#pragma startup func


#pragma exit func

void main(){
printf("\nI am in main");
getch();
}

RIET,CSE Page 21
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV

void func(){
printf("\nI am in func");
getch();
}

Following table will show you various directives

Directives Description

#define It substitutes a preprocessor macro.

#include It inserts a particular header file from another file.

#undef A preprocessor macro is undefined.

#ifdef It returns true if the macro is defined.

#ifndef It returns true if the macro is not defined.

#if It tests if the compile time condition is true.

#else It is an alternative for #if.

#elif It has #else and #if in one statement.

#endif The conditional preprocessor is ended.

#error It prints the error message on stderr.

#pragma It issues special commands to the compiler by using a standardized method.

RIET,CSE Page 22

You might also like