C – Union

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/c-union/
PINTEREST
PINTEREST
INSTAGRAM

C Programming Tutorial Index

  1. Introduction To Programming
  2. C Setup Development Environment
  3. C Hello World and Compile First Application
  4. C Syntax and Basics
  5. C Variables
  6. C Numeric Variable Types (Integer, Long, Float)
  7. C String Variables
  8. C Constants and Define Processor
  9. C Operators
  10. C If Else and Switch Case Conditionals
  11. C While Loops
  12. C For Loops
  13. C Arrays
  14. C Functions
  15. C Structure
  16. C Union
  17. C File Operations (Open, Read, Write)
  18. C Pointers
  19. C Type Casting
  20. C Header Files and Include

Union is a data type used to store different type of variables. Union is very similar to the struct but have some differences those have explained below. Union can contain int,char,float,… etc. in a single block. One union can contain single set of data at a time.

Defining Unions

Defining union is very similar to struct. We will use union statement. After union statement we will put union tag. After the tag we can put variables in curly brackets. Union tag is optional. Union variables will be automatically instantiated.

In this example we will define an union named MyData and a variable mydata.

After union definition we should also initialize some variable which is in union MyData type. We will initialize variable named mydata

Accessing Members

In this part we will access to the union members by using the name of the union variable and the member name. We can use this method both set and get member data. We will put a point between the union variable name and union member name like below.

LEARN MORE  Debugging Linux Bash Scripts

Below we can see an example where member variables data is set and get.

Structures vs Unions

As stated previously struct and union have syntax similarities. But the biggest difference is struct variables holds their members in separate memory areas but all same union variables will hold same memory areas. Simply single union type will hold single data for all union variables for the same type.

C Programming Tutorial Index

  1. Introduction To Programming
  2. C Setup Development Environment
  3. C Hello World and Compile First Application
  4. C Syntax and Basics
  5. C Variables
  6. C Numeric Variable Types (Integer, Long, Float)
  7. C String Variables
  8. C Constants and Define Processor
  9. C Operators
  10. C If Else and Switch Case Conditionals
  11. C While Loops
  12. C For Loops
  13. C Arrays
  14. C Functions
  15. C Structure
  16. C Union
  17. C File Operations (Open, Read, Write)
  18. C Pointers
  19. C Type Casting
  20. C Header Files and Include
RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/c-union/
PINTEREST
PINTEREST
INSTAGRAM

Leave a Reply

Your email address will not be published.