0% found this document useful (0 votes)
3 views28 pages

PSP Module 5

This document provides an overview of structures and pointers in C programming, detailing their definitions, features, and usage. It explains how to define and initialize structures, access their members, and utilize pointers for indirect memory access. Additionally, it covers concepts such as nested structures, arrays of structures, void pointers, and null pointers, along with example programs to illustrate these concepts.

Uploaded by

sudeepsbangera
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)
3 views28 pages

PSP Module 5

This document provides an overview of structures and pointers in C programming, detailing their definitions, features, and usage. It explains how to define and initialize structures, access their members, and utilize pointers for indirect memory access. Additionally, it covers concepts such as nested structures, arrays of structures, void pointers, and null pointers, along with example programs to illustrate these concepts.

Uploaded by

sudeepsbangera
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/ 28

PROBLEM SOLVING THROUGH PROGRAMMING

MODULE - V

DIGITAL NOTES
B.E
(I YEAR – II SEM)
(2021-22)

DEPARTMENT OF CSE
SHRI MADHWA VADIRAJA INSTITUTE OF
TECHNOLOGY AND MANAGEMENT

1
5.1. INTRODUCTION TO STRUCTURES
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.

In real life we need to have different data types for ex: To maintain employee information.
We should have information such as name, age, qualification, salary etc. here to maintain
the information of employee dissimilar data types required. Name & qualification are char
data type, age is integer, and salary is float. You can create this information separately but,
better approach will be collection of this information under single name because all these
information are related to person.

Structure is a collection of heterogeneous type of data i.e. different types of data. The
various individual components, in a structure can be accessed and processed separately. A
structure is a collection of variables referenced under a name, providing a convenient
means of keeping related information. A structure declaration forms a template that may
be used to create structure objects.

Difference between C variable, C array and C structure :

• A normal C variable can hold only one data of one data type at a
time. • An array can hold group of data of same data type.
• A structure can hold group of data of different data types
• Data types can be int, char, float, double and long double etc.

Features of Structures:
To copy elements of one array to another array of same data type elements are copied one
by one. It is not possible to copy elements at a time. Where as in structure it is possible to
copy the contents of all structure elements of different data types to another structure var
of its type using assignment (=) operator. It is possible because structure elements are
stored in successive memory locations. Nesting of structures is also possible.

2
5.1.1. Defining a structure:
‘struct’ keyword is used to define a structure, struct define a new data type which is a
collection of different type of data.
Syntax :
struct structure_name
{
//Statements
};
Example :
struct Book
{
char name[15];
float price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of
three data fields, namely name, price and pages. These fields are called structure elements
or members. Each member can have different data type, like in this case, name is of char
type and price is of float type etc. Book is the name of the structure and is called structure
tag.

5.1.2. Structure Initialization:

Like any other data type, structure variable can also be initialized at compile time.
Example :

struct Patient

{
float height;
int weight;
int age;

3
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

5.1.3. Accessing members of a structure:

There are two types of operators used for accessing members of a structure.

• Member operator (.)


• Structure pointer operator (◊)
Any member of a structure can be accessed as:
Syntax : structure_variable_name.member_name
Suppose, if we want to access age for variable p1. Then, it can be accessed as :
P1.age;
Program :WAP to define & initialize a structure & its variables
#include<stdio.h>
struct book
{
char book1 [30];
int pages;
float price;
};
main ( )
{
struct book bk1 = { “c++”, 300, 285};
printf (“ \n Book name : %s “ , bk1.book1);
printf (“\n No of pages :%d “,bk1.pages);
printf (“\n book price :%f “,bk1.price);
}
Output :
Book name: C ++
No of pages: 300
Book Price: 285

5.1.4. Nested structure

Nested structure in C is nothing but structure within structure. One structure can be
declared inside other structure. We can take any data type for declaring structure
members like int, float, char etc. In the same way we can also take object of one structure
as member in another structure.

Example:
struct student
{
char[30] name;
int age;
struct address
{
char[50] locality;
char[50] city;
int pincode;
};
};
Program : The following program is an example of nested structure in
c #include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;

int main()
{
struct student_detail stu_data = {1, \”sai”, 90.5, 1110,”sv University”};
printf(“ Id is: %d \n”, stu_data.id);
printf(“ Name is: %s \n”, stu_data.name);
printf(“ Percentage is: %f \n\n”, stu_data.percentage);
printf(“ College Id is: %d \n”, stu_data.clg_data.college_id);
printf(“ College Name is: %s \n”, stu_data.clg_data.college_name);
return 0;
}
Output :
Id is: 1
Name is: sai
Percentage is: 90.50000
College id is: 1110
College name is: Sv University

5.1.5. Pointer to a structure

It is also possible to create structure pointers. We can also create a pointer, pointing to
structure elements.
For this we require “->” operator.

The arrow operator (->) introduced in second version of C language, it is a shortcut


operator to access members of a structure through pointer.
If user-defined type is “struct student”, then its pointer type is “struct student*”

For example:
struct student *p; // p is a pointer variable to structure
P=&s1; //making pointer ‘p’ to s1

Now the expression “*p” accesses the total memory of “s1” The expression “(*p).id”
accesses the “id” in s1.
The expression “(*p).id” is equal to “p -> id”
The expression “(*p).name” accesses the “name” in s1.
“(*p).name” is equal to “p -> name”
Program : The following program is an example of a pointer to a structure.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1; //Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

strcpy( Book1.title, "C Programming");


strcpy( Book1.author, "vinay");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "naveen");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title); printf(
"Book author : %s\n", book->author); printf(
"Book subject : %s\n", book->subject); printf(
"Book book_id : %d\n", book->book_id); }
Output :
Book title: C Programming
Book author: vinay
Book subject: C Programming Tutorial
Book book_id: 6495407
Book title: Telecom Billing
Book author: naveen
Book subject: Telecom Billing Tutorial
Book book_id: 6495700
5.1.6. Array of structures
A structure is simple to define if there are only one or two element, but in case there are
too many objects needed for a structure, for ex. A structure designed to show the data of
each student of the class, and then in that case, the way will be introduced. A structure
declaration using array to define object is given below.

Initializing array of structures :


It is to be noted that only static or external variable can be initialized.

If incase, the
structure of object or any element of struct are not initialized, the compiler will automatically
assigned zero to the fields of that particular record.
Example :
employee data [3] = { { 146,’m’} ,{ 200, ‘f’ },{250 ,’m’}};
Compiler will assign :
data [0].sal=0; data [1].sal=0; data [2].sal=0;
Program :The program to initialize the array of structure members & display
#include<stdio.h>
void main ()
{
int i;
struct student
{
long int rollno;
char sex;
float height;
float weight;
};
struct student data [3] = { {121,’m’,5.7,59.8},{122,’f’,6.0,65.2},{123,’m’, 6.0, 7.5} };
clrscr ();
printf (“the initialized contents are:\n”);
for ( i=0; i< =2; i++)
{
printf (“%d/n ** Record is \n “, data [i].rollno);
printf (“%c\n“, data [i] .sex);
printf (“%f\n”, data [i].height);
printf (“%f\n”, data [i]. weight);
}
}
Output :
Output: The initialized contents are:
121
** Record is
m
5.700000
59.799999
122
** Record is
f
6.00000
65.19997
123
** Record is
m
6.000000
7.500000

5.2. INTRODUCTION TO POINTERS


Pointer is a special kind of variable used to store address of memory location through which
indirect memory accessing can be performed.

When variables are declared memory is allocated to each variable. C provides data manipulation
with addresses of variables therefore execution time is reduced. Such concept is possible with
special data type called pointer. A pointer is a variable which holds the address of another
variable or identifier this allows indirect access of data.

We know that memory is a collection of bits, in which eight-bits constitute one byte. Each byte has
its own unique location number called its “address”. To store this address we need a special kind
of variable called “pointer variable”.

To work with pointers we have two unary operators


1. Reference operator(&)
2. De-reference operator(*)
The ‘&’ and ‘*’ operators work together for referencing and dereferencing.

5.2.1. Reference operator (&) In C Language

This referencing operator is also called address operator, which gives the address of a variable,
in which location the variable is resided in the memory.

Syntax : &variable-name;

Example : int k=10;

Printf(“\n The address of k=%u”, &k);


Printf(“\n The value of k=%d”, k);
Output :
The address of k=2020
The value of k=10
• Here the expression ‘&k’ gives the address of ‘k’ in which it is stored, the format string %u or
%p is used to print address.
• Here the expression ‘&k’ is pronounced as “address of k”, the space for ‘k’ at run time may be
allocated anywhere in the RAM, and to get the address of ‘k’, reference operator is used.
• The address of a variable may not be a fixed location like 2020 above, and is randomly given by
the computer.

5.2.2. De-reference operator (*) In C Language

This operator is used to get the value at a given address. For example,*(2020)◊ 10; The

value at address 2020 is 10, this is k’s value

The action of ‘de-referencing operator’ is just contrary to the action of referencing


operator, this is also called ‘indirection operator’ as it changes the direction of control from
location to another location within the program’s memory to access the required data,

Syntax : *addressable _expression;


Example :
printf (“\n the value of k=%d”,*&k);//output=10
*&k -> *2020 -> 10
*&k -> k -> 10
The reference operator (&) gives the address of ‘k’, whereas de-reference operator (*)
gives value in that address, so finally it is ‘k’ value.

Declaration :
To differentiate ordinary variables from pointer variable, the pointer variable should
proceed by called “value at address operator”. It returns the value stored at particular
address. It is also called an indirection operator (symbol *).
Pointer variables must be declared with its type in the program as ordinary variables. Without
declaration of a pointer variable we cannot use in the program.
A variable can be declared as a pointer variable and it points to starting byte address of
any data type.

Syntax : data type *pointer variable;


The declaration tells the compiler 3 things about variable p
a) The asterisk (*) tells that variable p is a pointer variable.
b) P needs a memory location.
c) P points to a variable of type data type.
Example : int * p, v;
float *x;
In the first declaration v is a variable of type integer and p is a pointer variable. v stores
value, p stores address In the 2nd declaration x is a pointer variable of floating point data
type.
Pointer variables are initialized by p=&v, it indicates p holds the starting address of
integer variable v.

Let us assume that address of v is 1000.


This address is stored in p. Now p holds address of v, now *p gives the value stored at the
address pointer by p i.e. *p=20.

IMPORTANT POINTS :

1. A pointer variable can be assigned to another pointer variable, if both are pointing to the
same data type.
2. A pointer variable can be assigned a NULL value.
3. A pointer variable cannot be multiplied or divided by a constant.
Example : p*3 or p/3 where p is a pointer variable
4. C allows us to add integers to or subtract integers from pointers.
Example : p1+4, p2-2, p2-p1
If both p1, p2 are pointers to same way then p2-p1 gives the number of elements between p1, p2
5. Pointer variable can be incremented or decremented p++ & p- -

The values of a variable can be released in to way


1. By using variable name
2. By using adders.

Program : The following program is an example, to get a variable value by using


pointer #include<stdio.h>
main()
{
int k=10;
int *p;
p=&k;
printf(“\n *p=%d”,*p);
*p=20;
printf(“\n*p=%d”,*p);
printf(“\n k=%d”, k);
}
Output :
*p=10
*p=20
K=20

5.2.3. Void Pointers In C Language

We can declare a pointer to be of any data type void, and can assign a void pointer to any other
type.
It gives error because the pointer p is of type void and cannot hold any value. So, we have to type
cast the pointer variable from one type to other type.

The statement (int *) p makes p to become an integer type.


Program : The following program is an example of void pointer.
#include < stdio.h>
#include < conio.h>
main()
{
int x = 27;
void *p;
p= &x;
printf (“value is = %d”, * ((int *)p));
}
Output :
Value is 27

5.2.4. Null Pointer In C Language

• NULL Pointer is a pointer which is pointing to nothing.


• NULL pointer points the base address of segment.
• In case, if you don’t have address to be assigned to pointer then you can simply use NULL •
Pointer which is initialized with NULL value is considered as NULL pointer.

NULL is macro constant defined in following header files.

1. stdio.h
2. alloc.h
3. mem.h
4. stddef.h
5. stdlib.h

Examples of NULL pointer :

1. int *ptr=(char *)0;


2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;
Program : The following program is an example of null pointer.
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf(“The value of ptr is : %x\n”, ptr );
return 0;
}
Output :
The value of ptr is 0
On most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the memory
address 0 has special significance; it signals that the pointer is not intended to point to an
accessible memory location. But by convention, if a pointer contains the null (zero) value,
it is assumed to point to nothing.
To check for a null pointer you can use an, if statement as follows :
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

5.2.5. Pointer and functions In C Language

• Pointers can be passed as argument to a function definition.


• Passing pointers to a function is called call by reference.
• In call by reference whatever changes are made in formal arguments of the function
definition will affect the actual arguments in calling function.
• In call by reference the actual arguments must be pointers or references or addresses.
• Pointer arguments are use full in functions, because they allow accessing the original data in the
calling program.

Program : The following program is an example of pointer and


functions # include < stdio.h>
void swap (int *, int *);
main ( )
{
int a=10, b=20;
swap(&a, &b); /* a,b are actual parameters */
printf (“a= %d \t b=%d ”, a ,b);
}
void swap (int *x , int *y) /* x, y are formal parameters */
{
int t;
t = *x;
*x=*y;
*y=t;
}
Output :
a=20 b= 10
Program : The following program is an example of pointer to
functions. # include < stdio.h>
# include < conio.h>
void copy (char *, char *);
main ()
{
char a[20], b[20];
printf (“ Enter string
a:”); gets(a);
printf (“ Enter string
b:”); gets(b);
printf (“ Before copy “ );

printf (“ a=%s and b=%s ”, a ,


b); copy(a ,b);
printf (“After copy “);
printf (“ a=%s and b=%s”, a ,
b); }
void copy (char *x, char
*y) {
int i=0;
while ((X[i]=Y[i]) != “\0‟)
i++;
}
Output :
Enter string a: computer
Enter string b: science
Before copy
a=computer and b= science
After copy
a=science and b=science

5.2.6. Pointer and arrays In C Language

Pointer can be used with array for efficient programming. The name of an array itself indicates
the stating address of an array or address of first element of an array.

That means array name is the pointer to starting address or first elements of the array. If A is an
array then address of first element can be expressed as &A[0] or A. The Compiler defines array
name as a constant pointer to the first element.

Pointers and arrays are closely related, the array expressions can be taken as pointer expressions,
for example x[i] can be written as *(x+i)

Example : &x [0]->&*(x+0)_x therefore x->&x[0];

Hence, the expression “array name” without any index gives the address of first element
which is called base-address of array.

Assuming that the base address of arr is 1000 and each integer requires two byte, the five
elements will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e. 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented.
Program: The following program is an example of pointer arrays.
#include<stdio.h>
#include< conio.h>
void disp (int *, int);
main( )
{
int i, a[10],n;
printf (“ enter the size of an
array:”); scanf (“%d”, &n);
printf (“ enter the array
elements:”); for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
disp (a,n);
printf(“ array elements after sorting ”
); for(i=0;i<n;i++)
printf (“%d”, a[i]);
}

void disp(int a[ ], int n)


{
int i,j, temp;
for (i=0; i<n; i++)
for (j=0; j<n; j++)
{
if (a[j] > a[i])
{
temp = a[ j ];
a[ j ] = a[ i ];
a[ i ] = temp;
}
}
}
Output :
Enter the size of an array: 5
Enter the array elements: 20 30 10 50 40
Array elements after sorting: 10 20 30 40
50

5.2.7. Pointer and Character array In C Language

Pointer can also be used to create strings. Pointer variables of char type are treated as string.
Pointers are very useful in accessing character arrays. The character strings can be assigned with
a character pointer.

Example :
char array[ ] = “Love India”; //array version
char *str = "Hello";

This creates a string and stores its address in the pointer variable str. The pointer str now points
to the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.

char *str;
str = "hello"; //Legal
The content of the string can be printed using printf() and
puts(). printf("%s", str);
puts(str);

Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *.
Program : The following program is an example of pointer and character array.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = “\0”)
{
printf (“ %c “, *p);
p++;
}
}
Output :
Love India

5.2.8. Pointer Arithmetic In C Language


An integer operand can be used with a pointer to move it to a point / refer to some other address
in the memory.

In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2
bytes. But when we perform any arithmetic function like increment on a pointer, changes occur as
per the size of their primitive data type.
Consider an int type ptr as follows :

Assume that it is allotted the memory address 65494 increment value by 1 as follows.

++ and -- operators are used to increment, decrement a ptr and commonly used to move the ptr to
next location. Now the pointer will refer to the next location in the memory with address 65496.
C language automatically adds the size of int type (2 bytes) to move the ptr to the next memory
location.
mptr = mtpr + 1
= 65494 + 1 * sizeof (int)
= 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the
resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor. Scale factor is nothing but
the size of data type used in a computer.
We know that, the size of
float = 4
char = 1
double = 8 and so on

Rules for pointer operation :


The following rules apply when performing operations on pointer
variables
1. A pointer variable can be assigned to address of another variable.
2. A pointer variable can be assigned the values of other pointer variables.

3. A pointer variable can be initialized with NULL or 0 values.


4. A pointer variable can be prefixed or post fixed with increment and decrement operator. 5.
An integer value may be added or subtracted from a pointer variable.
6. When two pointers points to the same array, one pointer variable can be subtracted from
another.
7. When two pointers points to the objects of same data types, they can be compared using
relational
8. A pointer variable cannot be multiple by a constant.
9. Two pointer variables cannot be added.
10.A A value cannot be assigned to an arbitrary address.

5.3. C – PREPROCESSOR DIRECTIVES


Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with
“#” symbol.

5.3.1. List of preprocessor directives that C


programming language offers.
Preprocessor Syntax/Description

Macro Syntax: #define


This macro defines constant value and can be any of
the basic data types.

Header file inclusion Syntax: #include <file_name>


The source code of the file “file_name” is included in
the main program at the specified place.
Conditional compilation Syntax: #ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in
source program before compilation with respect
to the condition.

Other directives Syntax: #undef, #pragma


#undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after
main function in a C program.

A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.

There are 4 regions of memory which are created by a compiled C


program. They are,

∙ First region – This is the memory region which holds the executable code of the
program.
∙ 2 region – In this memory region, global variables are stored. ∙
nd
3rd region – stack
∙ 4th region – heap
5.3.2. Difference Between Stack & Heap Memory
Stack Heap

Stack is a memory region where “local Heap is a memory region


variables”, “return addresses of function which is used by dynamic
calls” and “arguments to functions” are hold memory
while C program is executed. allocation functions at run time.

CPU’s current state is saved in stack memory Linked list is an example


which uses heap memory.

5.3.3. Difference Between Compilers Vs Interpreters


Compilers Interpreters

Compiler reads the entire source Interpreter reads the program source
code of the program and converts it code one line at a time and executing
into binary code. This process is that line. This process is called
called compilation. interpretation.

Binary code is also referred as


machine code, executable, and object
code.

Program speed is fast. Program speed is slow.

One time execution. Interpretation occurs at every line of


Example: C, C++ the program.
Example: BASIC

Key Points to Remember:


∙ Source program is converted into executable code through different processes like precompilation,
compilation, assembling and linking.
∙ Local variables uses stack memory.
∙ Dynamic memory allocation functions use the heap memory.
Example Program For #DEFINE, #INCLUDE Preprocessors

∙ #define – This macro defines constant value and can be any of the basic data types. ∙
#include <file_name> – The source code of the file “file_name” is included in the main C
program where “#include <file_name>” is mentioned.

#include <stdio.h>

#define height 100

#define number 3.14

#define letter 'A'

#define letter_sequence "ABC"

#define backslash_char '\?'

void main()

printf("value of height : %d \n", height );

printf("value of number : %f \n", number );

printf("value of letter : %c \n", letter );

printf("value of letter_sequence : %s \n", letter_sequence);

printf("value of backslash_char : %c \n", backslash_char);

OUTPUT:

value of height : 100

value of number : 3.140000

value of letter : A

value of letter_sequence : ABC

value of backslash_char : ?
Example Program for Conditional Compilation Directives: A) EXAMPLE
PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:

“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If”
clause statements are included in source file.
Otherwise, “else” clause statements are included in source file for compilation and
execution.

#include <stdio.h>

#define RAJU 100

int main()

#ifdef RAJU

printf("RAJU is defined. So, this line will be added in " \

"this C file\n");

#else

printf("RAJU is not defined\n");

#endif

return 0;

OUTPUT:

RAJU is defined. So, this line will be added in this C file

B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:

#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If”
clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>

#define RAJU 100

int main()

#ifndef SELVA

printf("SELVA is not defined. So, now we are going to " \

"define here\n");

#define SELVA 300

#else

printf("SELVA is already defined in the program”);

#endif

return 0;

OUTPUT:

SELVA is not defined. So, now we are going to define here

C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:

“If” clause statement is included in source file if given condition is true. Otherwise, else
clause statement is included in source file for compilation and execution.

#include <stdio.h>

#define a 100

int main()

{
#if (a==100)

printf("This line will be added in this C file since " \

"a \= 100\n");

#else

printf("This line will be added in this C file since " \

"a is not equal to 100\n");

#endif

return 0;

OUTPUT:

This line will be added in this C file since a = 100

EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE:

This directive undefines existing macro in the program.

#include <stdio.h>

#define height 100

void main()

printf("First defined value for height : %d\n",height);

#undef height // undefining variable

#define height 600 // redefining the same for new value

printf("value of height after undef \& redefine:%d",height);

OUTPUT:
First defined value for height : 100

value of height after undef & redefine : 600

EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE:

Pragma is used to call a function before and after main function in a C program.

#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )

printf ( "\n Now we are in main function" ) ;

return 0;

void function1( )

printf("\nFunction1 is called before main function call");

void function2( )

printf ( "\nFunction2 is called just before end of " \

"main function" ) ;"

OUTPUT:

Function1 is called before main function call

Now we are in main function


Function2 is called just before end of main function

5.3.4. MORE ON PRAGMA DIRECTIVE IN C LANGUAGE:


Pragma command Description

#Pragma startup <function_name_1> This directive


executes function
named
“function_name_1”
before

#Pragma exit <function_name_2> This directive


executes function
named
“function_name_2”
just before
termination of
the program.

#pragma warn – rvl If function doesn’t


return a value, then
warnings are
suppressed by this
directive while
compiling.

#pragma warn – par If function doesn’t


use passed function
parameter , then
warnings are
suppressed

#pragma warn – rch If a non reachable


code is written
inside a
program, such
warnings are
suppressed by this
directive.

You might also like