4Unit 4

Structures, Unions & Enumerations

8h

Class hours

6

Topics

0%

0/6 done

Progress0/6 topics

Why This Unit Matters

Group related variables under one name using structures. Understand how unions share memory. Use enumerations to give symbolic names to integer constants.

Structures

C's primitive types (int, float, char) can only hold one kind of value. When you need to group related variables of different types under one name — such as a student's roll number, name, and marks — you use a structure (struct).

Defining and using a struct

  • Define the template with struct keyword and a tag name
  • Declare a variable of that struct type
  • Access members with the dot ( . ) operator
main.cStudent struct — input and pass/fail

Enter: 1 Ram 75.5 — the program stores and prints the student record.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

typedef struct — cleaner syntax

Using typedef lets you declare variables without repeating the struct keyword everywhere. It is the idiomatic style for larger programs.

main.ctypedef struct Employee

Shows how typedef removes the 'struct' keyword from variable declarations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"Define structure. Write a C program using structure to store student records (roll no., name, marks) and display them with pass/fail status" is a recurring 5-mark question.

Nested Structures

A nested structure is one where a struct is used as a member inside another struct. This models real-world relationships naturally — for example, an Employee record that contains a Date of Birth.

Member access with nested structs

emp.dob.year /* outer.inner.field — chained dot operators */
main.cEmployee with nested Date struct

Demonstrates struct-within-struct and chained dot-operator access.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

You can nest as many levels as needed. Each additional level just adds another dot in the access chain. typedef works the same way with nested structs.

Exam Tip

Nested structs are often combined with arrays of structures in exam questions. Know how to initialise a nested struct in a single statement and how to access fields using chained dots.

Arrays of Structures

Just as you can have an array of integers, you can have an array of structures. This is the standard C pattern for storing a list of records — student database, employee payroll, product catalogue, and so on.

Declaration

struct Student students[50]; /* array of 50 Student records */
students[0].roll = 1; /* access: array index then dot operator */
main.cArray of Student structs — tabular report

Enter 3 records: '1 Ram 75', '2 Sita 35', '3 Hari 88'

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

Bubble sort on an array of structs

You can sort an array of structures by any field — e.g. by marks in descending order. The swap operates on the entire struct, not just one field:

if (s[j].marks < s[j+1].marks) {
  struct Student temp = s[j];
  s[j] = s[j+1];  /* swap entire struct */
  s[j+1] = temp;
}
Exam Tip

"Write a C program using arrays of structures to store records of N students and display them in tabular form" is a common 5-mark question. Show the loop for both input and output.

Unions

A union looks like a struct, but all its members share the same memory location. The size of a union equals the size of its largest member. Only one member holds a valid value at any given time.

Structure vs Union — key difference

Featurestructunion
MemoryEach member has its own blockAll members share one block
SizeSum of all member sizes (+ padding)Size of the largest member
Simultaneous useAll members valid at onceOnly the last-assigned member is valid
Use caseGroup related fields of a recordSave memory; only one variant needed at a time
main.cunion Data — shared memory demonstration

Notice: after assigning d.f = 3.14, the value of d.i becomes garbage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

Memory layout (example)

struct Data: [ int(4) | float(4) | char(1) ] = 9+ bytes (with padding)
union Data: [ 4 bytes shared by all ] = 4 bytes
Exam Tip

"Differentiate between structure and union with a program and memory diagram" is a standard 5-mark question. Emphasise: union size = largest member, and only one member is valid at a time.

Enumerations

An enumeration (enum) assigns meaningful symbolic names to a sequence of integer constants. This makes code self-documenting and avoids magic numbers.

Syntax and default values

enum Color { RED, GREEN, BLUE }; /* RED=0, GREEN=1, BLUE=2 */
enum Month { JAN=1, FEB, MAR, APR }; /* explicit start at 1 */
  • By default the first enumerator is 0, each subsequent one increments by 1
  • You can override any value: enum Month { JAN=1, FEB, MAR } makes JAN=1, FEB=2, MAR=3
  • Enum variables are stored as int internally
  • Useful for state machines, days of week, menu choices, error codes
main.cenum Day — weekday vs weekend check

Enumerates days of the week and checks whether a given day is a weekday.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

TU exams sometimes ask "What is an enumeration? Write an example program using enum." Know that enum values are integers, that you can set explicit start values, and how to declare and use an enum variable.

Practice & Quiz

Active Recall Questions

Try to answer each question from memory before revealing the answer. This is the most effective study technique for long-term retention.

1

What is the difference between structure and union?

2

How do you access structure members using a pointer?

3

What is a nested structure?

4

What is an enum? Give an example.

5

What is the size of union { int i; float f; double d; }?

Exam-Style Questions

These questions match the style and marks distribution of TU BCA past papers. Attempt each question before revealing the full solution.

Write a C program using structure to store records of 5 students (name, roll, marks) and find the student with highest marks.

5 marks

Differentiate structure and union with syntax example and memory diagram.

5 marks

Write a C program using nested structure — Employee with name, id, and a Date struct (day, month, year for joining date). Store 3 employees and display them.

10 marks

How to Remember

How to Remember Unit 4

Structures and unions are conceptually similar but differ crucially in memory layout. These mnemonics and visual anchors will lock the distinctions into memory.

Mnemonics

struct vs union

"S for Separate, U for Unified"

Structure = Separate rooms — each member has its own dedicated space.

Union = one Unified room with different Uses — all members share the same space.

Think of a hotel: struct gives every guest their own room; union gives one room that different guests use at different times.

Arrow vs Dot operator

"Dot for Direct, Arrow for Address"

Dot (.) — you have the struct variable directly: s.name

Arrow (→) — you have a pointer to the struct: p->name

Arrow "points through" the pointer to reach the member — it derefs and accesses in one shot.

Memory Tricks

📐

struct size includes padding

struct size >= sum of member sizes because the compiler may add padding bytes for memory alignment. Use sizeof() to get the exact size — never calculate manually.

struct { char c; int i; } → NOT 5 bytes → likely 8 (padding added)
0️⃣

enum starts at 0 by default

enum counts from 0 like array indices unless you override with = value. First enumerator = 0, each subsequent one increments by 1 automatically.

enum Color { RED, GREEN, BLUE }; // RED=0, GREEN=1, BLUE=2
🏷️

typedef struct — drop the keyword

typedef lets you declare struct variables without repeating the "struct" keyword every time. Most real-world C code uses this pattern for cleaner declarations.

typedef struct Student Student; → write Student s instead of struct Student s
🤖

Union = Transformer toy

A union is like a transformer toy — same physical object, different forms. The memory location is constant; only the interpretation changes depending on which member you last wrote.

union { int i; float f; }; — writing f.float overwrites f.int's bits

Unit 4 — Before the Exam Checklist

Know how to define and declare a struct with multiple member types
Can access struct members with dot (.) and arrow (->) operators
Can write a nested struct (struct inside struct) and access with chained dots
Can declare and use an array of structures with loop for input/output
Know the memory difference: struct = sum of sizes, union = largest size
Can declare an enum with custom starting value and use it as a variable
Know that typedef removes the "struct" keyword from variable declarations
Can write a struct comparison table (struct vs union) for exam answers
BCAStudyHub

Your complete interactive study guide for TU BCA Semester I — covering all subjects with interactive tools, past papers, and exam prep.

TU BCASemester I

Program Info

University
Tribhuvan University
Program
BCA — Bachelor in Computer Application
Semester
I (First)
Subjects
5 (4 live, 1 coming soon)

Made by SawnN