Unit IV Part A - User Defined Data Types
Unit IV Part A - User Defined Data Types
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar
www.banday.in
• DATA IS STORED IN COMPUTER MEMORY USING VARIOUS REPRESENTATIONS.
DATA TYPES ARE VARIOUS SUCH METHODS.
• EACH DATA TYPE IS REPRESENTED IN MEMORY DIFFERENTLY AND DIFFERENT
OPERATIONS ARE ALLOWED UPON EACH.
• DATA TYPES CAN BE CLASSIFIED INTO TWO BROADER CATEGORIES NAMELY IN-
BUILT AND USER DEFINED DATA TYPES.
• IN-BUILT DATA TYPES ARE THOSE WHICH ARE DEFINED BY C COMPILER AND AS
www.banday.in
1
11/01/17
www.banday.in
USER DEFINED DATA TYPES
www.banday.in
• USER DEFINED DATA TYPES ARE CALLED DATA STRUCTURES (A LOGICAL METHOD
OF REPRESENTING DATA IN COMPUTER MEMORY).
• USER DEFINED DATA TYPES INCLUDE ARRAYS, STRUCTURES, UNIONS,
ENUMERATIONS, LINKED LISTS, STACKS, QUEUES, TREES, AND OTHERS.
• THIS PRESENTATION DISCUSSES
• STRUCTURES,
• UNIONS,
• ENUMERATIONS AND
www.banday.in
• BIT-FIELDS.
• OTHER DATA TYPES ARE COVERED IN DATA STRUCTURES TOPIC.
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
STRUCTURES
www.banday.in
2
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
• A STRUCTURES IS A HETEROGENEOUS, LINEAR AND STATIC DATA
STRUCTURE. IT IS OFTEN CALLED A RECORD.
• A STRUCTURE IS A DATA STRUCTURE IN WHICH EACH ITEM IS
IDENTIFIED BY ITS OWN IDENTIFIER EACH OF WHICH IS KNOWN AS A
MEMBER OF THE STRUCTURE.
• A MEMBER OF THE STRUCTURE MAY BE AN INBUILT DATA TYPE OR A
USER DEFINED DATA TYPE.
www.banday.in
Lecture Notes
A LINKED LIST OR SELF REFERENTIAL STRUCTURE.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• IN CASE A STRUCTURE INCLUDES A MEMBER WHICH IS A POINTER OF THE
SAME USER DEFINED DATA TYPE (STRUCTURE), THEN IT IS CALLED A LINKED
LIST OR SELF REFERENTIAL STRUCTURE.
• A STRUCTURE IS USEFUL IN PROGRAMS WHERE VARIOUS INDIVIDUAL DATA
ITEMS OF DIFFERENT DATA TYPES EXIST AND HAVE RELATIONSHIP WITH
EACH OTHER.
• STRUCTURES HELP IN MANAGING VARIOUS DATA ITEMS WHICH ARE
www.banday.in
3
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
• LEARNING STRUCTURES
• STRUCTURE DEFINITION
• STRUCTURE VARIABLE DECELERATIONS
• PROCESSING STRUCTURE VARIABLES
• NESTED STRUCTURES AND THEIR PROCESSING
• ARRAY OF STRUCTURES
• POINTERS AS STRUCTURE MEMBERS
www.banday.in
• TYPEDEF
• POINTER TO STRUCTURE
• PASSING STRUCTURES TO FUNCTIONS
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• STRUCTURE DEFINITION
• IN ORDER TO MAKE USE OF STRUCTURES, IT IS NECESSARY TO FIRST DEFINE THE
COMPOSITION OF STRUCTURE. THIS DEFINITION SERVES AS A TEMPLATE FOR FUTURE
DECELERATION OF VARIABLES. THE STRUCTURE DEFINITION DOES NOT RESERVE OR ALLOCATE
ANY MEMORY AT ALL.
• SYNTAX:
struct TAG {
MEMBER 1;
www.banday.in
MEMBER 2;
……….
MEMBER N;
};
4
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
struct TAG {
1. Is the required keyword for defining a structure.
1 2 MEMBER 1;
2. Is the name of the structure being defined. It is an
MEMBER 2;
3 identifier used to identify the structure and must
……….
confer to all naming rules and conventions set for
MEMBER N;
the identifiers.
};
3. Is the list of members enclosed within curly braces and terminated with a
terminator. Each of these members is a deceleration statement without any
initialization. These members may include inbuilt or user defined data types.
www.banday.in
Lecture Notes
member. It can be specified at the time of structure variable deceleration.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Example – Structure Definition
struct BOOK{
char Title [20]; In this example a structure namely BOOK having
char Author [20]; members namely Title, Author, Edition and Price is
int Edition; defined.
float Price;
};
unsigned int Day; members namely Title, Author, Edition and Price
unsigned int Month; is defined.
unsigned int Year;
};
5
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
• STRUCTURE VARIABLE DECELERATION
• IT IS A METHOD OF ASSOCIATING A VARIABLE OR A GROUP OF VARIABLES WITH A SPECIFIED
STRUCTURE TYPE. THE STRUCTURE MUST HAVE BEEN DEFINED PRIOR TO THIS AND MUST HAVE THE
SCOPE.
• SYNTAX:
storageclass struct structurename Var1[={values}], …. VarN[={values}];
1 2 3 4 5 6 7 8
1. Is the storage class spefier, which specifies where and how memory will be reserved for the variable(s). This is
optional.
2. Is the required keyword and must exist for all structure variable decelerations unless typedef statement is used.
3. Is the name of the structure that has already been defined. It may also be stated in the data type of the variables
www.banday.in
Lecture Notes
7. Is optional and similar to 4 and 5.
8. Is the required terminator.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Example – Structure Variable Deceleration
struct BOOK {
char Title [20]; struct BOOK BI;
char Author [20]; struct BOOK B2={“C Programming Lab”, “M T
int Edition; Banday”, 2015, 320.50};
float Price;
};
struct DATE {
www.banday.in
6
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
Example – Structure Variable Deceleration
struct DATE { A structure DATE is defined and two variables of this
unsigned int Day; structure namely DOB and CD are declared. The
individual members of the variable CD are initialized in
unsigned int Month;
the deceleration while as those of DOB remain
unsigned int Year; uninitialized.
}; The memory allocation for the deceleration assuming 2
bytes per unsigned int variable is 6 bytes for each
struct DATE DOB, CD={10, 10, 2016}; variable.
DOB CD
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Example – Structure Variable Deceleration
struct STUDENT{ The deceleration declares and initializes two structure
int RollNo; variables S1 and S2 of type STUDENT. One member is an
char Name[10]; integer and the other is an array and as such the
deceleration uses strings as the second member.
};
S1
RollNo Name
www.banday.in
0A00 0A02
12 Bytes
7
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
Combining Definition with the Deceleration
It is possible to combine the structure definition and structure variable deceleration in a single statement.
In such a case the name of structure is optional. However, if the structure name is not specified with such
combined structure definition and structure variable deceleration, it is not possible to declare the
variable of the same structure later in the program. The following examples illustrate such
struct { struct {
unsigned int Day; int RollNo;
unsigned int Month; char Name[10];
unsigned int Year; } S1={10,”Bilal”}, S2={11, “Andrew”};
Lecture Notes
} DOB, CD={10, 10, 2016};
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Example – Structure Variable Deceleration
struct STUDENT{ The deceleration declares and initializes two structure
int RollNo; variables S1 and S2 of type STUDENT. One member is an
char Name[10]; integer and the other is an array and as such the
deceleration uses strings as the second member.
};
S1
RollNo Name
www.banday.in
0A00 0A02
12 Bytes
8
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
• PROCESSING STRUCTURE VARIABLES
• MOST OF THE OPERATIONS INVOLVING STRUCTURE VARIABLE PROCESSING REQUIRE
INDIVIDUAL MEMBERS OF THE STRUCTURE TO BE PROCESSED AS SEPARATELY.
• THUS AN INDIVIDUAL STRUCTURE MEMBERS CAN BE ACCESSED BY USING A DOT OPERATOR
CALLED PERIOD.
• IT BELONGS TO THE HIGHEST OPERATOR PRECEDENCE GROUP AND HAS AN LEFT TO RIGHT
PRECEDENCE.
• IT IS ACCESSED IN THE FOLLOWING MANNER:
• structurevariable.member
www.banday.in
• SINCE THE . OPERATOR BELONGS TO THE HIGHEST PRECEDENCE GROUP AND HAS LEFT TO
RIGHT PRECEDENCE, TWO EXPRESSIONS LIKE ++structurevariable.member AND
++(structurevariable.member) ARE EQUIVALENT OR THE EXPRESSIONS
Lecture Notes
&structurevariable.member AND &(++structurevariable.member) ARE EQUIVALENT.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
CD
• PROCESSING STRUCTURE VARIABLES - EXAMPLES
Day Month Year
struct DATE { 10 10 2016
DOB
unsigned int Day; 0E00 0E02 0E04
Day Month Year
unsigned int Month; 6 Bytes
unsigned int Year;
0A00 0A02 0A04
};
6 Bytes
struct date DOB, CD={10,10,2016};
9
11/01/17
www.banday.in
USER DEFINED DATA TYPES - STRUCTURES
www.banday.in
• PROCESSING STRUCTURE VARIABLES - EXAMPLES
struct STUDENT {
int RollNo;
char Name[10];
};
struct STUDENT S2, S1={10,”Bilal”};
S1.Name ?
& S1.Name ?
strcpy(S2.Name,”Andrew”); ?
S2.Name[0] ?
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Processing Structure Variables – Example
struct student { scanf(“%d”,&s2.p1);
int rollno; printf(“\paper 2 marks: ”);
char fname[10]; scanf(“%d”,&s2.p2);
int p1, p2, total; s2.total = s2.p1 + s2.p2;
}; if(s1.total>s2.total)
main() printf(“\n %s topps %s by %d marks”, s1.name,
{ s2.name, s1.total-s2.total);
struct student s1={1, “bilal”,80, 85, 165}; else if(s2.total>s1.total)
struct student s2; printf(“\n %s topps %s by %d marks”, s2.name,
www.banday.in
10
11/01/17
www.banday.in
USER DEFINED DATA TYPES – NESTED STRUCTURES
www.banday.in
• STRUCTURE DEFINITIONS CAN BE NESTED IN OTHER
STRUCTURE DEFINITIONS CALLED NESTED STRUCTURES.
• INNER STRUCTURE DEFINITION
• THE STRUCTURE DEFNED WITHIN OTHER STRUCTURE DEFINITION
• OUTER STRUCTURE DEFINITION
• STRUCTURE DEFINITION CONTAINING OTHER STRUCTURE
www.banday.in
DEFINITIONS
• THE NAME OF THE INNER STRUCTURE DEFINITION IS
OPTIONAL.
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
example in this definition student is outer structure and dob
struct student { and marks are inner structure definitions which are
int rollno; nested inside the student structure.
char fname[10]; • decelerations and initilizations
int day, month, year; • struct student s1;
int marksp1, marksp2, marksp3;
};
• struct student s2 = {10, “bilal”, {1,1,1995},
The same structure could be more managebly
{80,80,90}};
defined as:
struct student {
• accessing members
www.banday.in
int rollno;
outerstructurevariable.innserstructurevariable.member
char fname[10];
e.g.
struct { int day, month, year; } dob;
s1.marks.marksp2 = 50; will assign 80 to marks of paper2
struct { int marksp1, marksp2, marksp3;}
of student s1.
marks; s2. dob.day will return 10. i.e. the day of birth of student
}; s1
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
11
11/01/17
• EXAMPLE USES
• student s1 = {11, “bilal”, {10,10,1980}, {1,1,2015}, {50,48}, {25,34}};
• student s2;
• s2.rollno=22;
• strcpy(s2.fname,”amin”);
• s2.dob.day=15
• s2.doa.year=2015;
Lecture Notes
• s2.theory.marksp1=67;
Dr. M Tariq Banday, University of Kashmir, Srinagar
12
11/01/17
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar
13
11/01/17
Lecture Notes
S.DOB.day, S.DOB.month, S.DOB.year );
Dr. M Tariq Banday, University of Kashmir, Srinagar
14
11/01/17
Lecture Notes
} }
Dr. M Tariq Banday, University of Kashmir, Srinagar
15
11/01/17
Lecture Notes
>member[expression].
With respect to the above statements, following expressions evaluate to the shown values:
PS = 0F00 S =*PS = 1 *PS = 1 &S.rollno = 0F00
&S.fname = 0F02 &S.fname[1] = 0F03 S.rollno = 1 S.fname = OF02
S.fname[1] = I (*PS).rollno=1 (*PS).fname[1]=I PS->rollno=1
S.dob.year=1990 (*PS).dob.year=1990 PS->dob.year=1990 &PS->dob.day=0F0C
16
11/01/17
void main()
{
struct Marks { int rollno; int marksp1; int marksp2;};
struct Marks ClassA[5];
Struct Marks *ptr, *ptrH, *ptrL;
for(ptr=classA;ptr<ClassA+5;ptr++){ printf(“\Roll No: “); scanf(“%d”,ptr->rollno); printf(“\nMarks
p1”); scanf(“%d”, ptr->marksp1); printf(“\nMarks p2”); scanf(“%d”, ptr->marksp2);}
ptrH=ptrL=ClassA; ptr=ClassA+1;
while(ptr<ClassA+5) { if(ptrH->marksp1+ptrH->marksp2<ptr->marksp1+ptr->marksp2) ptrH=ptr;
if(ptrL->marksp1+ptrL->marksp2<ptr->marksp1+ptr->marksp2) ptrL=ptr;}
printf(“\nHighest Marks %d secured by student bearing roll no %d”, ptrH->marksp1+ptrH-
>marksp2, ptrF->rollno);
printf(“\nLowest Marks %d secured by student bearing roll no %d”, ptrL->marksp1+ptrL->marksp2,
ptrL->rollno);
Lecture Notes
}
17
11/01/17
• struct Account { int ActNo; char *Name; char *Address; long Amount;};
• struct Account A1;
A1.ActNo = 802
A1.Amount = 3000;
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar
18
11/01/17
Lecture Notes
printf(“\nname ?”); }
19
11/01/17
• Typedef is a storage class specifier which defines identifiers that name types and does
not declare objects.
• These identifiers are called typedef names.
• Once an typedef name is defined, it is syntactically equivalent to a type specifier
keyword for the associated type.
• Although typedef names are usually created for user defined data types created with
struct keywor, yet typedef names can also be created for inbuilt data types. The
syntax for using typedef is as follows:
Typedef type newdatatypename
E.G
typedef int INTEGER; INTEGER Num, *P;
Lecture Notes
typedef float real; real Rate, temp;
20
11/01/17
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS
www.banday.in
• A bit field is a set of adjacent bits within a single word of memory. (A word being
a single implementation defined storage unit).
• Bit fields provide exact amount of bits required for storage of values.
• Some data items in a program may have only a limited domain of values.
Declaring such data items as individual variables will allocate at least a word
from memory for each such variable, thus wasting memory. E.g. a Flag indicating a
true value by 1 and false value by 0 requires only one bit in memory. Declaring it
as a variable of type int will allocate 16 bits for it. Similarly an integer variable
www.banday.in
whose value can range between 0 to 7 only requires three bits in memory.
• Bit fields provide a method for packing such data items in an individual word(s) of
memory. Thus multiple data items may be allocated memory from single word of
www.banday.in
• The minimum amount of memory allocated is a word even if the total amount of
bits required by the data items packaged int a group is less that the no of bits in
a word.
• In case it is more that a word but less that its integer multiply the amount of
memory allocated will remain the immediate next integer multiply.
• Bit fields are defined as the members of a structure in a structure definition which
can be later accessed individually by method similar to other structure members.
• Each member deceleration (a bit field) includes a colon (:) and unsigned integer as
www.banday.in
21
11/01/17
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS
www.banday.in
• A bit field can only be defined from an integer or an unsigned word. Some
compilers also permit allocation of bits from long integer and character.
• Bit fields can be accessed in a manner same as other structure members are
accessed, however, there are certain restrictions on the use of bit fields which
include:
• Bit fields cannot be arrays, i.e. a member declared as a bit field cannot be an array.
• The use of the address operator (&) is not allowed with a bit field.
• A bit field cannot be accessed via a pointer.
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Example: bit field definitions & deceleration
struct sample {
unsigned a: 1;
• This defines four bit fields named a, b, c and d, of 1, 3, 2 and 1 bits
unsigned b: 3;
each in a structure named sample. Thus as many as 7 bits are
unsigned c: 2;
required for storing the values of these bit fields.
unsigned d: 1
};
• Thus a deceleration struct sample s = {0,3,2,1}; will reserve one word (usually 16 bits) from memory
abd allocate bits as described in the bit field definition to each bit field. The bits may be allocated from left
to right or from right to left depending upon the compiler and machine.
www.banday.in
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 1 0 0 1 1 0
Unused Bits d c b a
• As can be seen from the graphics only seven bits are committed while as remaining 9 bits remain
uncommitted. Besides these bit fields are also initialized to the values shown.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
22
11/01/17
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS
www.banday.in
• Example: bit field definitions & deceleration
struct sample {
unsigned a: 6;
• This defines five bit fields named a, b, c, d and e, of 6. 4, 5, 4 and 5
unsigned b: 4;
bits each in a structure named sample.
unsigned c: 5;
unsigned d: 4;
unsigned e: 5;
};
• Thus a deceleration struct sample s = {6,4,5,4,5}; will reserve two words from memory (in case the
word size is 16 bits). The first three bit fields namely a, b and c will be allocated memory from the first word
www.banday.in
and the last two namely d and e will be forced to second word.
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Lecture Notes
Unused Bits e d c b a
www.banday.in
• Example: bit field definitions & deceleration
Sometimes, it may be desired to align a bit field to a new word and skipping the available
bits within the current word.
Consider definition of three bit fields of 5 bits each, thus requiring a total of 15 bits which
can be reserved from one word. However, if it is desired to align the last bit field to another
word, the following definition may be used:
struct sample { struct sample {
unsigned a: 5; unsigned a: 5;
unsigned b: 6; unsigned b: 6;
Unsigned Filler: 6;
www.banday.in
Unsigned : 0;
unsigned c: 5; unsigned c: 5;
}; };
• To align the bit field, a filler or an unnamed field with zero width can be used.
23
11/01/17
www.banday.in
USER DEFINED DATA TYPES – BITFIELDS
www.banday.in
• Example: printf(“\nrollno ? :”);
scanf(“%d”, &temp); s[i].rollno=temp;
struct marks { print(“\nname ?”);
unsigned th: 7; gets(s[i].name); fflush(stdin);
unsigned pr: 7; printf(“\ntheory marks ?”);
unsigned tot: 8; scanf(“%d”,&temp); s[i].m.th=temp;
unsigned per: 7; …...
unsigned res: 3; .......
}; s[i].m.tot=s[i].m.th + s[i].m.pr;
typedef struct { }
unsigned rollno: 4;
char fname[10]; for (i=0;i<10;i++)
struct marks m; {
} student;
www.banday.in
Lecture Notes
for (i=0;i<10;i++)
{
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Passing Structures to Functions
• C permits a function to pass structures as arguments to
another function and also permits a function to return a
structure.
• Structures can be passed to function in three ways:
• By passing individual members of structure, e.g.
www.banday.in
24
11/01/17
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES
www.banday.in
• Passing Structures to Functions - passing individual members
• This method is the most elementary one and has no or very little practical significance because
it becomes unmanagable and inefficient when dealing with a large structure.
#include <stdio.h> printdistance(d1.feet, d1.inch);
typedef { printdistance(d2.feet, d2.inch);
int feet; }
int inch;
} distance; void printdistance (int f, int i)
www.banday.in
www.banday.in
• Passing Structures to Functions - passing copy of the entire structure
• It is much efficient an manageable.
25
11/01/17
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES
www.banday.in
• Passing Structures to Functions - passing copy of the entire structure
• It is much efficient an manageable.
void printdistance (distance d) distance adddistances(distance d1, distance d2)
{ {
printf(“\nfeets = %d”, d.feet); distance temp;
printf(“\ninchs = %d”, d.inch); temp.feet=d1.feet+d2.feet;
} temp.inch=d1.inch+d2.inch;
distance readdistance(void) while(temp.inch>=12)
{ {
www.banday.in
Lecture Notes
return(d); }
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Passing Structures to Functions – by passing copy pointer to a structure
• It is much efficient an manageable.
26
11/01/17
www.banday.in
USER DEFINED DATA TYPES – STRUCTURES
www.banday.in
• Passing Structures to Functions – by passing pointer to a structure
• It is much efficient an manageable.
void printdistance (distance *d);
{ void adddistances(distance *d1, distance *d2,
printf(“\n feets = %d”, d->feet); distance *d3);
printf(“\n inchs = %d”, d->inch); {
} d3->feet=d1->feet+d2->feet;
void readdistance(distance *d); d3->inch=d1->inch+d2->inch;
{ while(d3->inch>=12)
www.banday.in
Lecture Notes
} }
www.banday.in
• Exercise: Using structures and functions, add as many as 10 distances
stored in an array.
• Exercise: Using structures and functions repeat the student program to
calculate marks and grades.
www.banday.in
27
11/01/17
www.banday.in
USER DEFINED DATA TYPES – UNIONS
www.banday.in
• A union data type is borrowed from structures data type and is similar
to variant record type of Pascal language.
• A union is essentially a structure in which all of the fields overlay each
other and only one can be used at a time. Members of the union share
memory.
• The size of the union is the maximum of the sizes of its individual
members, whereas the size of the structure is the sum of the sizes of its
www.banday.in
individual members.
• Unlike structure variables, for a union variable all members begin at
Lecture Notes
offset zero from the base address.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Although a union can have many members but it can hold only one
member at a time.
• Unions provide a way to manipulate different kinds of data in a single
area of storage. i.e. a single variable that can hold any one of several
data types.
• The method of defining a union is same as that of a structure except a
distinction that the struct keyword is replaced by union keyword. The
www.banday.in
members of union may include inbuilt or other user defined data types
like structures.
• Similarly union variable deceleration is similar to that of structures.
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
28
11/01/17
www.banday.in
USER DEFINED DATA TYPES – UNIONS
www.banday.in
• A union may be initialized only with a value of the type of its first
member.
• All operations that are permitted on a structure variable are
permissible with union variables including assignment, accession union
members, use of address (&) operator, (->) operator, etc.
• Unions can be nested in structures and visa versa.
• It is permissible to have union of structures, and bit fields in unions.
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Consider the following example definition of Union:
union Example {
int ival;
float fval;
0F01 0F02 0F03 0F04 0F05 0F06 0F07 0F08
double dval;
ival
char *Sval;
fval
};
dval
union Example u1 = 10;
Sval
union Example u2;
www.banday.in
29
11/01/17
www.banday.in
USER DEFINED DATA TYPES – UNIONS
www.banday.in
• Example
union allowance{
float GPF;
float PF;
};
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• An enumeration is a user defined data type with values ranging over a set of named
constants. These constants are called enumeration variables and are of type int.
• An enumeration variable can be assigned any value from the corresponding set of
enumerators.
• Enumerators in the same scope must be distinct from each other and also from ordinary
variable names.
• The values however can be same for two enumerators. The general syntax for defining an
enumeration is:
• enum tag { enumurator1=[value1], enumurator2=[value2], …......
www.banday.in
enumuratorn=[valuen]};
• Enumuration variables can be declared with the following syntax:
• Storageclass enum tag variable1, varaible2, ....variablen;
30
11/01/17
www.banday.in
USER DEFINED DATA TYPES – ENUMERATION
www.banday.in
• Examples
• enum DAYS{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
• The constant values assigned to each enumerator are 0, 1, 2, 3, 4, 5, 6, respectively.
• enum DAYS BEGIN, END
• Assignments in the program can be used like
• Begin = Monday
• End = Sunday
• enum DAYS{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
Begin, End;
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
• Examples
• enum {NO, YES} Answer;
• enum {OM, SC, ST, OBC} Category ;
• enum {Singly, Married, Widowed, Divorced} Status ;
• enum {False, True} TF;
• enum color {RED =10, GREEN, BLUE};
• enum color Foreground, Background
#include <stdio.h>
enum {NO, YES} Answer;
void main()
www.banday.in
{
Answer = NO;
printf(“The answer is %d”, Answer);
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
31
11/01/17
www.banday.in
BIT WISE OPERATORS
www.banday.in
• Bitwise operators permit manipulation of bits stored in the memory
which is considered to be a low-level feature found mostly in low level
programming languages such as assembly languages.
• These operators treat variables as combinations of bits rather than as
numbers.
• They are useful in accessing the individual bits in memory such as the
screen memory etc.
www.banday.in
Lecture Notes
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
www.banday.in
Operator Meaning Example
~ Ones Complement ~0XF1 returns 0XFF0E (hex)
~0361 returns 0177416 (octal)
~11110011 returns 00001100 (binary)
& Bitwise AND 0XF1 & 0X35 returns 0X31 (hex)
0361 & 0065 returns 061 (octal)
11110011 & 00110101 returns 00110011 (binary)
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
www.banday.in
32
11/01/17
www.banday.in
BIT WISE OPERATORS
www.banday.in
Decimal to Binary Conversion using Bit-Wise Operators
#include <stdio.h>
int main()
{
int n, c, k;
printf("enter an integer in decimal number system\n");
scanf("%d", &n); printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
www.banday.in
else
printf("0");
}
printf("\n");
Lecture Notes
return 0;
}
Dr. M Tariq Banday, University of Kashmir, Srinagar www.banday.in
ANY QUESTIONS
THANK YOU
33