0% found this document useful (0 votes)
2 views

ENG1410 CProgramming Topic10b Enum Union

The document covers user-defined data types in C programming, specifically focusing on typedef, enum, and union. It explains the syntax and usage of these types, highlighting their importance in creating complex programs and improving code readability. Additionally, it provides examples and resources for further learning.

Uploaded by

rangavennela369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ENG1410 CProgramming Topic10b Enum Union

The document covers user-defined data types in C programming, specifically focusing on typedef, enum, and union. It explains the syntax and usage of these types, highlighting their importance in creating complex programs and improving code readability. Additionally, it provides examples and resources for further learning.

Uploaded by

rangavennela369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

ENG1410

C Programming: Topic #10


“C: User Defined Types
(typedef, enum, union)”
S. Areibi
School of Engineering
University of Guelph
Topics
 Introduction
 User Defined Data Types
 Typedef
 Enum
 Unions
 ….
Textbook Resources

 Chapter #13, #16


Introduction
C BASIC (DATA) TYPES
In C, data type categorized as:

1. Primitive Types in ANSI C (C89)/ISO C (C90) -


char, short, int, float and double.
2. Primitive Types added to ISO C (C99) -
long long
3. User Defined Types –
struct, union, enum and typedef
4. Derived Types –
pointer, array and function pointer.

5
Data Types
 What is a Data Type?
o Defines a certain domain of values
o Defines Operations allowed on these values
 Example
1. int type
o Takes only integer values
o Operations: addition, subtraction, multiplication, bitwise
operations e.t.c
2. float type
o Takes only floating point values
o Operations: addition, subtraction, multiplication, division
e.t.c (bitwise and % operations are not allowed).

6
Primitive Data Types
• Almost all programming languages provide
a set of primitive data types
• Primitive data types: Those not defined in
terms of other data types
• Some primitive data types are merely
reflections of the hardware
• Others require only a little non-hardware
support for their implementation

7
User Defined Data Types
o In contrast to primitive data types, there is a concept
of user defined data types.
o The operations and values of user defined data types
are not specified in the language itself but is specified
by the user.
o Examples of user defined data types include:
1. Typedef: C provides a capability that enables users to assign
an alternate name to a data type. This is done with a
statement known as typedef
2. Structure: by using structures, we are defining our own type
by combining other data types.
3. Enum: types are defined and used by the programmer as
need arises.
4. Union: is one of the more advanced programming applications in
which it is necessary to store different types of data in the same
storage area.

8
Typedef
Type Definition
• Syntax: typedef type Name ;
• Name becomes a name you can use for the type
• Examples:
typedef int INTEGER;
INTEGER x; /* x is an integer */
typedef char *STRING;
STRING sarray[10];
/* sarray is an array of char *’s, equivalent to declaring:
char *sarray[10]; */

10
Typedef
• Definition:– a typedef is a way of renaming a
type

• E.g.,
typedef struct motor Motor;

Motor m, n;
Motor *p, r[25];
Motor function(const Motor m; …);

11
typedef (continued)
• typedef may be used to rename any type
– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
– Portability across platforms
• E.g.,
– typedef char *String;
• E.g.,
– typedef int size_t;
– typedef long int32;
– typedef long long int64;

12
“enum” Data Type
Enum Data Types
 enum is a user-defined type consisting of a set of named
constants called enumerators.
 Using a keyword enum, it is a set of integer constants
represented by identifiers.
 The syntax is shown below, ([is optional])
// for definition of enumerated type
enum [tag]
{
enum-list
}
[declarator];

 And
// for declaration of variable of type tag
enum tag declarator;

 These enumeration constants are, in effect, symbolic


constants whose values can be set automatically.
14
Enum Data Types: Declaring
 The values in an enum start with 0, unless specified
otherwise, and are incremented by 1. For example,
the following enumeration,
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

 Creates a new data type, enum days, in which the


identifiers are set automatically to the integers 0 to 6.
 To number the days 1 to 7, use the following
enumeration,
enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};

 Or we can re-arrange the order,


enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};
15
Enum Data Types: Variables

enum day {sun, mon, tue, wed, thu, fri, sat};

The keyword enum is used to declare an enumeration type.

The enumerators above are the identifiers sun, mon,...,sat.

The keyword enum along with the tag name day are used as
a type specifier to declare variables of type enum day.

enum day d1, d2; /* declares variables d1 & d2 */

16
Alternative var Declaration
On the previous slide, the enumeration type
enum day was first declared, then variables of
that type were declared.
o We can do both at the same time.

enum day {sun,mon, tue, wed, thu, fri, sat} d1, d2;

17
Enum Data Types: What Are they?

enum day {sun, mon, tue, wed, thu, fri, sat} d1;

 The enumerators sun, mon, ..., sat are identifiers:


 They are constants of type int.

 By default, the first one is given the value 0,


and each succeeding one has the next integer.

18
Enum Data Types: Initialization

enum fruit {apple = 7,pear, orange = 3,lemon} fruit;

o Since the enumerator apple has been initialized to


7, pear has a value of 8.

o Since orange has a value of 3, lemon has a value


of 4.

19
Enum Data Types: Example
// An example program to demonstrate working
// of enum in C
#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main() Output?:


{
enum week day; The day is: 2
day = Wed;
printf(“The day is:%d",day);
return 0;
}

20
Enum Data Types: Example
// Another example program to demonstrate
// working of enum in C
#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,


Aug, Sep, Oct, Nov, Dec};

int main() Output?:


{
int i;
0 1 2 3 4 5 6 7 8 9 10 11
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

return 0;
}

21
“union” Data Type
Union Data Types
 One of the more unusual constructs in the C programming
language is the union.
 This construct is used in applications in which it is necessary
to store different types of data in the same storage area.
 For example if you want to define a single variable called x,
which could be used to store (a) a single character, (b) a
floating point member, or (c) an integer, you could define a
union say called mixed as follows:

union mixed We can now declare a variable to be of type


{ union mixed as  union mixed x;
char c;
float f; However, this declaration does not define x to
int I; contain three distinct members called c, f and i.
} rather it defines x can be used to store either a
char, or a float, or an int but not all three
23
Union Data Types
 A union is a user-defined data or class
type that, at any given time, contains only
one object from its list of members
(although that object can be an array or a
class type).
union [tag] { member-list } [declarators];

 Then, in program we can declare union


type variable as,
[union] tag declarators;

24
Union Data Types
 The storage associated with a union variable is
the storage required for the largest member of
the union.
 When a smaller member is stored, the union
variable can contain unused memory space.
 All members are stored in the same memory
space and start at the same address.
 Hence, the stored value is overwritten each time
a value is assigned to a different member.
 Begin the declaration of a union with the union
keyword, and enclose the member list in curly
braces.
25
Union Data Types
 Union are particularly useful in embedded programming or in situations
where direct access to the hardware/memory is needed depending on
the endianism and processor architecture.
 For example, union can be used to breakdown hardware registers into
the component bits. So, you can access an 8-bit register bit-by-bit.
 Unions are used when you want to model struct defined by hardware,
devices or network protocols, or when you are creating a large number
of objects and want to save space.
 In most occasion of the program running, you really don't need them
90% of the time. (just an assumption!)
 Most of the cases the union is wrapped in a struct and one member
of the struct tells which element in the union to access.
 In effect, a union is a structure in which all members have offset zero
from the base.
 The same operations are permitted on union as on struct:
assignment to or copying as a unit, taking the address, and accessing a
member.

26
union Data Types: Example
#include <stdio.h>
#include <string.h>
union Record {
int i;
float f;
char str[20];
};
int main( ) {
The system will print:
union Record record; // var declaration
record.i : 1917853763
record.f : 4122360580327794
record.i = 10;
record.str : C Programming
record.f = 220.5;
strcpy( record.str, "C Programming");

printf( "record.i : %d\n", record.i);


printf( "record.f : %f\n", record.f);
printf( "record.str : %s\n", record.str);

return 0;
}
27
union Data Types: Example
#include <stdio.h>
#include <string.h>
union Record {
int i;
float f;
char str[20];
};
int main( ) {

union Record record; // var declaration


The system will print:
record.i = 10;
printf( "record.i : %d\n", record.i); record.i : 10;
record.f = 220.5; record.f : 220.5;
printf( "record.f : %f\n", record.f); record.str : C Programming

strcpy( record.str, "C Programming");


printf( "record.str : %s\n", record.str);

return 0;
}
28
Summary
Summary
o User Defined Data Types are a powerful constructs
to build more complex programs.
o User Defined Data Types in “C” can be any of the
following types:
o enum: is used to assign names to the integral constants
which makes a program easy to read and maintain.
o struct: structures are aggregate data types. They are useful
for many applications such as databases, banking and
many others.
o union: Unitions allow you to create variables which share a
common memory space. Unions are a bit like structures, in
that they appear to be aggregate data types. However, the
main difference is that the union members occupy
overlapping memory areas.
 typedef: Programmers typically use typedef keyword to
improve the readability of the code and as a means of
abbreviating it.
30
Resources
Union/Enum: Resources
o YouTube:
 https://www.youtube.com/watch?v=9QdJExC2AVg
 https://www.youtube.com/watch?v=oySsPUDr35U

o Documents:
 https://docs.microsoft.com/en-us/cpp/c-language/c-enumeration-
declarations?view=msvc-160
 https://www.tutorialspoint.com/cprogramming/c_unions.htm

o Examples:
 https://www.programiz.com/c-programming/c-enumeration
 https://www.geeksforgeeks.org/enumeration-enum-c/
 https://www.programiz.com/c-programming/c-unions

o Test Yourself:
 https://www.prep.youth4work.com/practice-_test_s/c-programming-
test/structures__comma__-unions-and-enumerations-test

32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy