SlideShare a Scribd company logo
1 of 14
CSC 2O3: COMPUTER PROGRAMMING 1
C Unions
DR(MRS) O.E.OJO
Union in C
• A union is a special data type available in C
• that allows to store different data types
• in the same memory location.
• A union can be defined with many members,
• but only one member can contain a value at any given
time.
Union in C
• Unions provide an efficient way of
• using the same memory location
• for multiple-purpose.
• To define a union,
• you must use the union statement
• in the same way while defining a structure.
The union statement defines a new data type with more
than one member for your program.
The format of the union statement is as follows
Defining a Union
.
union [union tag] {
member definition;
member definition;
…
member definition;
} [one or more union variables];
• The union tag is optional
• and each member definition is a normal variable
definition,
• such as int i; or float f; or any other valid variable
definition.
• At the end of the union's definition, before the final
semicolon,
• you can specify one or more union variables but it is
optional.
Here is the way to define a union type named Data having
three members i, f, and str
.
union Data {
int i;
float f;
char str[20];
} data;
• Now, a variable of Data type can store an integer, a
floating-point number, or a string of characters.
• It means a single variable, that is, same memory
location, can be used to store multiple types of data.
• You can use any built-in or user defined data types
inside a union based on your requirement.
• The memory occupied by a union will be large enough
to hold the largest member of the union.
• For example, in the above example,
• Data type will occupy 20 bytes of memory space
because this is the maximum space which can be
occupied by a character string.
Output
The following example displays the total memory size occupied:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %dn", sizeof(data));
return 0;
}
Accessing Union Members
To access any member of a union, we use the member access
operator (.).
The member access operator is coded as a period between the
union variable name and the union member.
The keyword union is used to define variables of union type.
//C program example on how to use Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
return 0;
}
When the above code is compiled and executed, it produces the
following result
Here, we can see that the values of i and f members of
union got corrupted
because the final value assigned to the variable has
occupied the memory location
and this is the reason that the value of str member is
getting printed very well.
Now let's look into the same example once again where
we will use one variable at a time which is the main
purpose of having unions
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
When the above code is compiled and executed, it produces the
following result
Here, all the members are getting printed very well because one member
is being used at a time.

More Related Content

Similar to Unions.pptx

Similar to Unions.pptx (20)

UNIONS IN C.pptx
UNIONS IN C.pptxUNIONS IN C.pptx
UNIONS IN C.pptx
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
Unions
UnionsUnions
Unions
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Structure & union
Structure & unionStructure & union
Structure & 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...
 
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
 
UNIONS.pptx
UNIONS.pptxUNIONS.pptx
UNIONS.pptx
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Union.ppt
Union.pptUnion.ppt
Union.ppt
 
Unit 3
Unit 3Unit 3
Unit 3
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Session 6
Session 6Session 6
Session 6
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Unit 1_ADC.pptx
Unit 1_ADC.pptxUnit 1_ADC.pptx
Unit 1_ADC.pptx
 
structures and unions in 'C'
structures and unions in 'C'structures and unions in 'C'
structures and unions in 'C'
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
 
F# Console class
F# Console classF# Console class
F# Console class
 

Recently uploaded

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Unions.pptx

  • 1. CSC 2O3: COMPUTER PROGRAMMING 1 C Unions DR(MRS) O.E.OJO
  • 2. Union in C • A union is a special data type available in C • that allows to store different data types • in the same memory location. • A union can be defined with many members, • but only one member can contain a value at any given time.
  • 3. Union in C • Unions provide an efficient way of • using the same memory location • for multiple-purpose. • To define a union, • you must use the union statement • in the same way while defining a structure.
  • 4. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows Defining a Union . union [union tag] { member definition; member definition; … member definition; } [one or more union variables];
  • 5. • The union tag is optional • and each member definition is a normal variable definition, • such as int i; or float f; or any other valid variable definition. • At the end of the union's definition, before the final semicolon, • you can specify one or more union variables but it is optional.
  • 6. Here is the way to define a union type named Data having three members i, f, and str . union Data { int i; float f; char str[20]; } data; • Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. • It means a single variable, that is, same memory location, can be used to store multiple types of data.
  • 7. • You can use any built-in or user defined data types inside a union based on your requirement. • The memory occupied by a union will be large enough to hold the largest member of the union. • For example, in the above example, • Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.
  • 8. Output The following example displays the total memory size occupied: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); return 0; }
  • 9. Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member. The keyword union is used to define variables of union type.
  • 10. //C program example on how to use Union #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str); return 0; }
  • 11. When the above code is compiled and executed, it produces the following result
  • 12. Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions
  • 13. #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; }
  • 14. When the above code is compiled and executed, it produces the following result Here, all the members are getting printed very well because one member is being used at a time.