SlideShare a Scribd company logo
1 of 5
Union
• A union is declared using the keyword union as:
union student
{
char name[20];
int roll_no;
float marks;
char section;
};
union student s;
• While accessing union members, we should make sure that
we are accessing the member whose value is currently
residing in the memory. Otherwise we will get erroneous
output (which is machine dependent).
2
Unions:
• A union is a variable that may hold (at different
times) objects of different types and sizes, with the
compiler keeping track of size and alignment
requirements.
• Unions provide a way to manipulate different kinds
of data in a single area of storage, without
embedding any machine-dependent information in
the program.
• Both structure and unions are used to group a
number of different variables together.
Syntactically both structure and unions are exactly
same. The main difference between them is in
storage.
• In structures, each member has its own memory
location but all members of union use the same
memory location which is equal to the greatest
member’s size.
3
Example: program illustrates the structure in which read member elements of union and display
them.
#include<stdio.h>
union Student
{
char name[20];
int roll;
char sec;
F loat marks;
};
union Student s1;
void main()
{
printf(“Enter the name of a student”);
gets(s1.name);
printf(“Enter the roll number of a student”);
scanf(“%d”,&s1.roll);
printf(“Enter the section of a student”);
scanf(“%c”,&s1.sec);
printf(“Enter the marks obtained by the student”);
scanf(“%f”,&s1.marks);
/displaying the records
printf(“Name=%sn Roll number =%dn Section=%cn Obtained marks=%f”,s1.name,
s1.roll, s1.sec, s1.marks);
}
4
Example:
union student
{
char name[20];
int roll_no;
float marks;
char section;
};
void main()
{
union student s;
clrscr();
printf("Size of union=%dn", sizeof(s));
strcpy(s.name, “cnr");
printf("Name=%st", s.name);
printf("Location=%u", s.name);
s.roll_no=10;
printf("nRoll=%d tLocation=%u", s.roll_no, &s.roll_no);
s.marks=91.5;
printf("nMarks=%.2f tLocation=%u", s.marks, &s.marks);
s.section='A';
printf("nSection=%c tLocation=%u", s.section, &s.section);
printf("nnErroneous output");
printf("nnNametRolltMarkstSectionn");
printf("%st%dt%.2ft%c", s.name, s.roll_no, s.marks, s.section);
getch();
}
5

More Related Content

What's hot (20)

Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
 
Strings in C
Strings in CStrings in C
Strings in C
 
structure and union
structure and unionstructure and union
structure and union
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Array ppt
Array pptArray ppt
Array ppt
 
Array in c
Array in cArray in c
Array in c
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Lecture19 unionsin c.ppt
Lecture19 unionsin c.pptLecture19 unionsin c.ppt
Lecture19 unionsin c.ppt
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Structure in C
Structure in CStructure in C
Structure in C
 
Strings
StringsStrings
Strings
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 

Viewers also liked (20)

Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods
 
Recursion transformer
Recursion transformerRecursion transformer
Recursion transformer
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
Input output streams
Input output streamsInput output streams
Input output streams
 
C tutorial
C tutorialC tutorial
C tutorial
 
Secondary storage structure
Secondary storage structureSecondary storage structure
Secondary storage structure
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
The Algebra of Functions
The Algebra of FunctionsThe Algebra of Functions
The Algebra of Functions
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
C string
C stringC string
C string
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Secondary storage structure-Operating System Concepts
Secondary storage structure-Operating System ConceptsSecondary storage structure-Operating System Concepts
Secondary storage structure-Operating System Concepts
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Storage Class in C Progrmming
Storage Class in C Progrmming Storage Class in C Progrmming
Storage Class in C Progrmming
 
Structure in c
Structure in cStructure in c
Structure in c
 

Similar to Union in C programming

Union from C and Data Strutures
Union from C and Data StruturesUnion from C and Data Strutures
Union from C and Data StruturesAcad
 
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptx
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptxUnit_6StructureandUnionpptx__2023_01_04_16_48_56.pptx
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptxvekariyakashyap
 
UNIONS IN C.pptx
UNIONS IN C.pptxUNIONS IN C.pptx
UNIONS IN C.pptxSKUP1
 
UNIONS IN C.pptx
UNIONS IN C.pptxUNIONS IN C.pptx
UNIONS IN C.pptxLECO9
 
Union
UnionUnion
UnionAcad
 
Union in c language
Union in c languageUnion in c language
Union in c languageTanmay Modi
 
Structures unions
Structures  unionsStructures  unions
Structures unionsSugnan M
 
Useful and Effectiveness of Multi Agent System
Useful and Effectiveness of Multi Agent SystemUseful and Effectiveness of Multi Agent System
Useful and Effectiveness of Multi Agent Systemijtsrd
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and UnionSelvaraj Seerangan
 
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...ssuser5610081
 

Similar to Union in C programming (20)

Union from C and Data Strutures
Union from C and Data StruturesUnion from C and Data Strutures
Union from C and Data Strutures
 
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptx
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptxUnit_6StructureandUnionpptx__2023_01_04_16_48_56.pptx
Unit_6StructureandUnionpptx__2023_01_04_16_48_56.pptx
 
UNIONS IN C.pptx
UNIONS IN C.pptxUNIONS IN C.pptx
UNIONS IN C.pptx
 
UNIONS IN C.pptx
UNIONS IN C.pptxUNIONS IN C.pptx
UNIONS IN C.pptx
 
UNION 1.pptx
UNION 1.pptxUNION 1.pptx
UNION 1.pptx
 
Union
UnionUnion
Union
 
Union in c language
Union in c languageUnion in c language
Union in c language
 
Unions.pptx
Unions.pptxUnions.pptx
Unions.pptx
 
17 structure-and-union
17 structure-and-union17 structure-and-union
17 structure-and-union
 
C- language Lecture 7
C- language Lecture 7C- language Lecture 7
C- language Lecture 7
 
Union.ppt
Union.pptUnion.ppt
Union.ppt
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
C programming session7
C programming  session7C programming  session7
C programming session7
 
C union
C unionC union
C union
 
Structures unions
Structures  unionsStructures  unions
Structures unions
 
Useful and Effectiveness of Multi Agent System
Useful and Effectiveness of Multi Agent SystemUseful and Effectiveness of Multi Agent System
Useful and Effectiveness of Multi Agent System
 
Operating systems1[1]
Operating systems1[1]Operating systems1[1]
Operating systems1[1]
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...
Data Types in C++-Primary or Built-in or Fundamental data type Derived data t...
 

More from Kamal Acharya

Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computerKamal Acharya
 
Introduction to Computer Security
Introduction to Computer SecurityIntroduction to Computer Security
Introduction to Computer SecurityKamal Acharya
 
Making decision and repeating in PHP
Making decision and repeating  in PHPMaking decision and repeating  in PHP
Making decision and repeating in PHPKamal Acharya
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in phpKamal Acharya
 
Text and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHPText and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHPKamal Acharya
 
Capacity Planning of Data Warehousing
Capacity Planning of Data WarehousingCapacity Planning of Data Warehousing
Capacity Planning of Data WarehousingKamal Acharya
 
Information Privacy and Data Mining
Information Privacy and Data MiningInformation Privacy and Data Mining
Information Privacy and Data MiningKamal Acharya
 
Association Analysis in Data Mining
Association Analysis in Data MiningAssociation Analysis in Data Mining
Association Analysis in Data MiningKamal Acharya
 
Classification techniques in data mining
Classification techniques in data miningClassification techniques in data mining
Classification techniques in data miningKamal Acharya
 
Introduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data WarehousingIntroduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data WarehousingKamal Acharya
 

More from Kamal Acharya (20)

Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computer
 
Computer Arithmetic
Computer ArithmeticComputer Arithmetic
Computer Arithmetic
 
Introduction to Computer Security
Introduction to Computer SecurityIntroduction to Computer Security
Introduction to Computer Security
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Web forms in php
Web forms in phpWeb forms in php
Web forms in php
 
Making decision and repeating in PHP
Making decision and repeating  in PHPMaking decision and repeating  in PHP
Making decision and repeating in PHP
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 
Text and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHPText and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Capacity Planning of Data Warehousing
Capacity Planning of Data WarehousingCapacity Planning of Data Warehousing
Capacity Planning of Data Warehousing
 
Data Warehousing
Data WarehousingData Warehousing
Data Warehousing
 
Search Engines
Search EnginesSearch Engines
Search Engines
 
Web Mining
Web MiningWeb Mining
Web Mining
 
Information Privacy and Data Mining
Information Privacy and Data MiningInformation Privacy and Data Mining
Information Privacy and Data Mining
 
Cluster Analysis
Cluster AnalysisCluster Analysis
Cluster Analysis
 
Association Analysis in Data Mining
Association Analysis in Data MiningAssociation Analysis in Data Mining
Association Analysis in Data Mining
 
Classification techniques in data mining
Classification techniques in data miningClassification techniques in data mining
Classification techniques in data mining
 
Data Preprocessing
Data PreprocessingData Preprocessing
Data Preprocessing
 
Introduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data WarehousingIntroduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data Warehousing
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

Union in C programming

  • 2. • A union is declared using the keyword union as: union student { char name[20]; int roll_no; float marks; char section; }; union student s; • While accessing union members, we should make sure that we are accessing the member whose value is currently residing in the memory. Otherwise we will get erroneous output (which is machine dependent). 2
  • 3. Unions: • A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. • Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program. • Both structure and unions are used to group a number of different variables together. Syntactically both structure and unions are exactly same. The main difference between them is in storage. • In structures, each member has its own memory location but all members of union use the same memory location which is equal to the greatest member’s size. 3
  • 4. Example: program illustrates the structure in which read member elements of union and display them. #include<stdio.h> union Student { char name[20]; int roll; char sec; F loat marks; }; union Student s1; void main() { printf(“Enter the name of a student”); gets(s1.name); printf(“Enter the roll number of a student”); scanf(“%d”,&s1.roll); printf(“Enter the section of a student”); scanf(“%c”,&s1.sec); printf(“Enter the marks obtained by the student”); scanf(“%f”,&s1.marks); /displaying the records printf(“Name=%sn Roll number =%dn Section=%cn Obtained marks=%f”,s1.name, s1.roll, s1.sec, s1.marks); } 4
  • 5. Example: union student { char name[20]; int roll_no; float marks; char section; }; void main() { union student s; clrscr(); printf("Size of union=%dn", sizeof(s)); strcpy(s.name, “cnr"); printf("Name=%st", s.name); printf("Location=%u", s.name); s.roll_no=10; printf("nRoll=%d tLocation=%u", s.roll_no, &s.roll_no); s.marks=91.5; printf("nMarks=%.2f tLocation=%u", s.marks, &s.marks); s.section='A'; printf("nSection=%c tLocation=%u", s.section, &s.section); printf("nnErroneous output"); printf("nnNametRolltMarkstSectionn"); printf("%st%dt%.2ft%c", s.name, s.roll_no, s.marks, s.section); getch(); } 5