1 / 6

Introduction to Union Type in C

Learn about union data structure in C that allows for different components to vary depending on the value of another component. Understand how to define and manipulate unions to store data efficiently. Avoid common errors by utilizing contextual statements.

ssawyers
Download Presentation

Introduction to Union Type in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSci 160Lecture 44 Martin van Bommel

  2. Union Introduction • So far, all variables of a particular structure type have exactly the same components • Sometimes we need a structured type in which some components vary depending on the value of another component • e.g. data stored about a geometric figure depends on the type of figure

  3. Union Type • C provides a union data structure typedef union { int num; char ch[2]; } int_ch_t; • Variables of this type represent either an integer or two characters • Need some other value to determine which

  4. Union Storage • What if parts of union not same memory size? typedef union { int num1; double num2; } num_t; • When create a variable, how large in memory? • Size of largest part of union (e.g. 8 bytes)

  5. Geometric Figures • For problem with geometric figures, first define structures for each type of figure • Then define a union type with a component for each figure type • Finally define structure containing both a component of the union type and a component whose value denotes which is the correct interpretation of union • See program geometry.c

  6. Union Problems • Most common error with union types is referencing a component that is not currently valid • Helpful to place in another structure with component whose value indicates correct interpretation • Then all manipulation done within context of if or switch statement

More Related