Join Communities

Search Notes Gallery

Home / BCA / Problem Solving Using C Unit 4 Notes – Structures, Unions, Enum and Storage Classes

Problem Solving Using C Unit 4 Notes – Structures, Unions, Enum and Storage Classes

NotesGallery
Dec 5, 2026 • 44 min read
Problem Solving Using C Unit 4 Notes Source: NotesGallery

Course Code: BBC103

Course: AKTU BCA 1st Year, Semester I

Unit: Structures, Unions, Enum and Storage Classes

Unit IV Overview

Study user-defined record types, structure operations, nested and array records, structure pointers, shared union storage, enumerated states and the four storage classes specified in the AKTU syllabus.

Topics Covered

Syllabus area Pages
Structure definition and member access 2-5
Structure operations and memory 6-7
Nested records and arrays 8-10
Structure pointers and functions 10-12
Unions: declaration, operations and usage 12-15
Enumerated data types 16-17
Storage classes and integrated examples 17-24
Exam questions with answers 25-27
Quick revision and key formulas 28

Learning Outcomes

  • 1. Define and initialize structures.

  • 2. Access members and perform record operations.

  • 3. Use nested records, arrays and structure pointers.

  • 4. Explain union storage and applications.

  • 5. Declare and trace enumerated types.

  • 6. Distinguish all four storage classes.

Included in These Notes

28 study sections; 34 labelled diagrams; 10 colourful context images; explained C programs; worked cases; comparison tables, 24 short answers and 6 structured long answers and quick revision.

Study Approach

Understand. Identify fields, types, visibility and object lifetime.

Compare. Distinguish structure and union; compare storage classes.

Apply. Trace record updates and output of each C example.

Core idea: Structures group fields; unions share storage; enums name choices; storage classes control declaration behavior.

1. Introduction to structures

A structure is a user-defined aggregate type that groups related objects, called members, under one name. Unlike an array, the members may have different types. A student record, for example, can contain an integer roll number, a character array for the name and a floating-point mark.

A student record.

Why structures are useful

  • They model records that belong together, such as students, employees, books and products.

  • They improve clarity by attaching meaningful member names to values.

  • They allow an entire record to be passed to a function, copied, or stored in an array.

Array Structure
Homogeneous elements Members may differ in type
Access by index Access by member name
int a[5] struct Student s
Arrays cannot be assigned Same-type structures can be assigned

Do not confuse a structure type with a structure variable. A type describes the record format; a variable stores an instance of that type.

An identification record groups several related attributes. Illustrative image.

Real-world modelling

An admission system must maintain a student’s roll number, name and marks together. Three unrelated variables make it difficult to manage multiple students. A record type gives each student the same logical format while keeping each student’s actual values independent.

Independent records.

Memory representation

Each ordinary member occupies its own storage inside the object. Members appear in declaration order, but the compiler may insert padding for alignment. The object size is therefore not necessarily the sum of its members’ sizes.

Exam tip: A structure is heterogeneous; an array is homogeneous. A structure is a record, not a collection of identically typed elements.

Exam Check

Give two reasons for using a structure instead of separate variables. Answer: Related data stays together and named fields make the record clear.

2. Defining and declaring a structure

General syntax

struct Student {
int roll;
char name[30];
float marks;
};

The keyword struct begins the definition. Student is a tag, and the declarations between braces describe the members. The terminating semicolon is mandatory. The definition of a tag alone does not create an object. Allocate objects by declaring them using the type.

struct Student s1;
struct Student s2, s3;

Type and instances.

Definition with variable declaration

struct Point {
int x;
int y;
} p1, p2;

This defines the tagged type and declares two Point objects. The tag can be used later as struct Point.

typedef and anonymous types

typedef struct {
int day;
int month;
int year;
} Date;
Date d;

The typedef introduces Date as an alias for the structure type. It does not allocate an object or create a new distinct type.

Syntax Meaning
struct Point Tagged type specifier
struct Point p Declare an object p
typedef … Date Introduce a type alias
Date d Declare an object d

Member declarations may include arrays, other structures, pointers and enumerated types. A structure cannot contain a complete object of its own type directly, because that would require an infinite object size.

struct Node {
int value;
struct Node *next;
};

A self-referential pointer is permitted because a pointer has a finite size. The structure definition can refer to the incomplete tag while declaring the pointer.

Exam Check

Does a structure definition itself allocate a record? Answer: A tag definition describes a type; a separate object declaration allocates storage.

3. Initializing structure variables

Positional initialization

struct Student {
int roll;
char name[20];
float marks;
};
struct Student s = {101,”Asha”,86.5f};

The initializer values correspond to members in declaration order. The string literal initializes the character array, including its null terminator.

Positional initialization.

If fewer initializers are supplied, the remaining members are initialized as if they had static storage duration: arithmetic members become zero, pointers become null, and aggregates are recursively initialized.

struct Student t = {102};
struct Student zero = {0};

Do not assume an uninitialized automatic structure has all-zero contents. Its members may have indeterminate values.

Separate employee folders illustrate independent records. Illustrative image.

Designated initialization (C99)

Designators explicitly identify the member being initialized. They avoid dependence on the ordering of other members and improve readability.

struct Student r = {
.name = “Riya”,
.marks = 92.0f,
.roll = 103
};

Initialization Effect
{101,”Asha”,86.5f} All members initialized in order
{102} Remaining members zero-initialized
{0} Members recursively zero-initialized
{.marks=90.0f} Named member specified

Memory trick

Declare with struct and a tag, initialize with braces, access using the dot operator. These are three separate steps. Always check that an initializing string fits the character array.

Exam Check

What value does an omitted numeric member get in a partial initializer? Answer: Zero.

4. Accessing structure members

The member access operator is a dot (.). Write the structure object name followed by a dot and a valid member name.

s.roll = 101;
s.marks = 86.5f;
printf(“%d”, s.roll);
printf(“%.1f”, s.marks);

Dot access.

An expression such as s.marks is an lvalue when s is a suitable modifiable object. It may be assigned, read, used in arithmetic or passed to a function.

Character array member: You cannot assign a string literal to an array member after declaration. Use a suitable copying operation with enough capacity.

#include <string.h>
strcpy(s.name, “Asha”);

The destination name array must hold all characters plus the terminating null. A pointer member, in contrast, can be assigned a compatible pointer value.

Program: initialize and print

#include <stdio.h>
struct Student {
int roll;
char name[20];
float marks;
};
int main(void){
struct Student s={17,”Neha”,88};
printf(“%d %s %.1f”,
s.roll,s.name,s.marks);
return 0;
}

Output: 17 Neha 88.0

Input with member addresses

scanf(“%d”, &s.roll);
scanf(“%19s”, s.name);
scanf(“%f”, &s.marks);

For numeric members, provide their addresses. The character array name converts to a pointer to its first element. The field width limits this example to 19 visible characters. Check scanf return values before using input; use fgets for a full name containing spaces.

Exam Check

Access the roll member through an object s. Answer: s.roll.

5. Operations on individual members

Members behave like ordinary objects of their declared type. Numeric members support arithmetic, relational and assignment operations. Character arrays support indexed access and compatible string functions.

s.marks += 5.0f;
s.roll++;
if(s.marks >= 75)
puts(“Distinction”);

Updating marks.

Member expressions can also participate in calculations across records. The following calculates the average of two students’ marks.

float avg=(s1.marks+s2.marks)/2;
printf(“%.2f”,avg);

Comparing members

if(s1.roll == s2.roll)
puts(“Same roll number”);

For string contents, use strcmp rather than comparing the addresses of name arrays.

An invoice illustrates updating one numeric record field. Illustrative image.

Program: employee salary

#include <stdio.h>
struct Employee {
int id;
float basic, allowance;
};
int main(void){
struct Employee e={5,20000,4500};
float gross=e.basic+e.allowance;
printf(“%.2f”,gross);
return 0;
}

Output: 24500.00

Operation Example
Assignment e.basic = 22000
Addition e.basic + e.allowance
Comparison e.basic > 20000
Increment e.id++
String comparison strcmp(a.name,b.name)

When operating on a member, apply the rules of that member’s own type. Avoid integer division when the desired result is fractional. Individual members can be copied, compared or updated independently.

Exam Check

If basic pay is 20000 and allowance 4500, gross pay is 24500.

Complete member-update application

Create a library book record with an accession number, title, price and number of available copies. Borrowing a copy changes only the availability member; the other fields remain associated with the book.

#include <stdio.h>
struct Book{
int accession,copies;
char title[24];
double price;
};
void borrow(struct Book *b){
if(b->copies>0)–b->copies;
}
int main(void){
struct Book b={52,3,”C Notes”,150};
borrow(&b);
printf(“%d %d %.2f”,b.accession,
b.copies,b.price);
return 0;
}

Output: 52 2 150.00.

Field Before After
accession 52 52
copies 3 2
title C Notes C Notes
price 150 150

A record update should alter only the field corresponding to the operation. If the number of available copies is already zero, borrow leaves the object unchanged. Design functions around the record’s intended rules rather than changing fields arbitrarily.

Separate concerns

The Book type defines storage, the borrow function expresses the operation, and main provides a sample object and prints its results. Keeping these concerns separate makes later record-array operations simpler.

6. Operations on entire structures

Assignment and copying

struct Point {int x,y;};
struct Point a={3,4};
struct Point b={0,0};
b=a;

Assignment between compatible structure types copies the member values, including array members. After copying, changing b.x does not change a.x.

Structure assignment.

If a structure holds a pointer member, assigning the structure copies the pointer value, not the object to which it points. Both pointer members may therefore refer to the same object. This is often called a shallow copy.

Operation Whole structure allowed?
Assignment = Yes: compatible types
Initialization by structure Yes: compatible expression
Arithmetic + or – No
Equality == or != No
sizeof Yes
Address & Yes

Comparing and passing structures

To test logical equality, compare each relevant member. Do not use memcmp as a general equality test because padding bytes and representations may differ.

int equal(struct Point a,
struct Point b){
return a.x==b.x && a.y==b.y;
}

Return a structure

struct Point add(struct Point a,
struct Point b){
struct Point r={a.x+b.x,
a.y+b.y};
return r;
}

Passing a structure by value creates a parameter object initialized from the argument. Returning a structure returns its value. Both operations are supported by standard C.

Worked case: add({3,4},{5,2}) conceptually produces a Point with x=8, y=6. In actual C, use variables or compound literals of the correct structure type.

Exam Check

Can a structure with an array member be copied by assignment? Answer: Yes, if the structure types are compatible.

7. Structure memory, size and alignment

Each member receives storage inside the structure, in its declaration order. To meet alignment requirements, an implementation may insert padding between members or after the last member.

struct Sample {
char c;
int i;
char d;
};

Example byte regions.

Assume a platform with one-byte char and four-byte int aligned at a multiple of four bytes. A possible layout is c at offset 0, i at offset 4, d at offset 8, and total size 12. This is an example, not a portable guarantee.

Finding the actual size

printf(“%zu”,sizeof(struct Sample));

sizeof returns a size_t value representing the object’s size in bytes. Use %zu to print it in C99 and later.

Checking offsets

#include <stddef.h>
printf(“%zu”,offsetof(

struct Sample,i));

offsetof from stddef.h gives the byte offset of a named ordinary member. Do not use it on bit-fields.

Example layout Offset Bytes
c 0 1
Padding 1 3
i 4 4
d 8 1
Tail padding 9 3
Total 0 12

Why padding exists

Aligned accesses satisfy the target’s requirements. Tail padding ensures that elements of an array of structures can each begin at a suitable boundary. Reordering members sometimes changes size, but portability requires measuring, not assuming.

Do not send raw structure bytes as a portable record format without accounting for alignment, byte order and representation. For examination problems, state the alignment assumptions clearly.

Exam Check

Why does total size include tail padding? Answer: To help successive array elements meet alignment requirements.

Worked alignment comparison

Suppose char has width and alignment 1, int has width and alignment 4, and double has width and alignment 8.

struct A{char c;double d;int i;};
struct B{double d;int i;char c;};

Under these assumptions, A places c at 0, d at 8, i at 16 and ends at offset 24 after padding. B places d at 0, i at 8 and c at 12, with final size 16. These are possible layouts for the assumed rules; verify actual results with sizeof.

Member A offset B offset
c 0 12
d 8 0
i 16 8
Total bytes 24 16
Example layout B.

Array stride

An array of four B records has a possible size 64 bytes if sizeof(struct B) is 16. Record number 2 starts at byte offset 32, and its int member at offset 40. The actual stride equals sizeof(struct B).

Avoid binary serialization based on a guessed layout. Different implementations may represent members and padding differently. Even on one system, reordering declarations can change the record’s binary layout and affect compatibility.

8. Nested structures

A structure can contain another complete structure as a member. This groups related details within a larger record.

struct Date {int d,m,y;};
struct Student {
int roll;
char name[20];
struct Date dob;
};

Nested student record.

Initializing a nested record

struct Student s={
21,”Ravi”,{12,8,2006}
};

The inner braces initialize the Date member’s day, month and year. Access nested members by chaining dot operators.

printf(“%d”,s.dob.y);
s.dob.m=9;

The output before the update is 2006; the month becomes 9.

Nested travel organisers illustrate a record within a record. Illustrative image.

Program: display a date

#include <stdio.h>
struct Date{int d,m,y;};
struct Book{
char title[20];
struct Date published;
};
int main(void){
struct Book b={“C Basics”,
{10,5,2025}};
printf(“%s: %d-%d-%d”,
b.title,b.published.d,
b.published.m,b.published.y);
return 0;
}

Output: C Basics: 10-5-2025

Date member expansion.

Use nested records when a member has multiple related attributes, such as an address, date, time or coordinate. An array of structures may itself contain nested structures.

Exam Check

Access year in a nested date d within s. Answer: s.d.y if the members have those names.

9. Arrays of structures

An array of structures stores several objects of the same structure type in consecutive array elements. Each element is a complete record, not a single member.

struct Student {
int roll;
char name[20];
float marks;
};
struct Student a[3];

Array of student records.

Initializing an array

struct Student a[3]={
{1,”Asha”,82},
{2,”Ravi”,76},
{3,”Neha”,93}
};

Use the index to select a record, then the dot operator to select its member.

printf(“%s”,a[1].name);
a[2].marks=95;

The first expression prints Ravi. The second changes the marks of the third record.

Ordered index cards illustrate an array of complete records. Illustrative image.

Traversing records

for(int i=0; i<3; ++i){
printf(“%d %s %.1f\n”,
a[i].roll,a[i].name,a[i].marks);
}

Index Name Marks
0 Asha 82
1 Ravi 76
2 Neha 93

Finding the highest score

int best=0;
for(int i=1;i<3;i++){
if(a[i].marks>a[best].marks)
best=i;
}
printf(“%s”,a[best].name);

The loop inspects each student and maintains the index of the highest-marked record. When marks are equal, the earlier record remains selected. For a general algorithm, verify that the array is nonempty before reading its first element.

Exam point: An array stores homogeneous elements; a structure stores heterogeneous members. An array of structures combines both ideas.

Exam Check

Select the second record and its name. Answer: a[1].name.

10. Searching and sorting record arrays

Searching by roll number

int find(struct Student a[],
int n,int roll){
for(int i=0;i<n;i++)
if(a[i].roll==roll) return i;
return -1;
}

The function accepts an array parameter, which adjusts to a pointer, and the count of records. It returns the first matching index, or -1 if the roll number is not found.

Search for roll 2.

Do not confuse an index with a stored roll number. The second record may have roll number 2, but its array index is 1.

Sorting by marks

for(int i=0;i<n-1;i++){
for(int j=0;j<n-1-i;j++){
if(a[j].marks<a[j+1].marks){
struct Student t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}

This bubble sort arranges records in descending order of marks. Swapping entire structures keeps the name, roll number and marks associated correctly.

Pass Marks sequence
Initial 82 76 93
First 82 93 76
Second 93 82 76

Never swap only marks when ranking students, because names would no longer correspond to their real marks. For the three records, the final order is Neha, Asha, Ravi.

Complexity: The simple nested-loop version uses O(n squared) comparisons in the worst case and one temporary record.

Exam Check

Why swap whole records? Answer: To keep fields belonging to each person together.

Compute class statistics from records

Instead of sorting student data, compute total marks and count students who meet a threshold. The input records do not change.

#include <stdio.h>
struct Student {int roll;float m;};
int main(void){
struct Student a[]={{1,78},
{2,65},{3,91},{4,50}};
float total=0;int pass=0;
for(int i=0;i<4;i++){
total+=a[i].m;
if(a[i].m>=60)pass++;
}
printf(“%.2f %d”,total/4,pass);
return 0;
}

Output: 71.00 3.

Roll Marks Meets threshold
1 78 Yes
2 65 Yes
3 91 Yes
4 50 No

The loop selects a record with a[i] and accesses only the marks field. The record array remains in its original order. This differs from sorting, which reorders complete record objects.

Exercise: filtered record display

To print only qualifying student IDs, traverse the array, check each record’s marks and display the roll number when the condition is true. The filtering condition controls output, not array capacity or the number of records stored.

11. Pointers to structures

A pointer to a structure stores the address of an object of the corresponding structure type.

struct Point {int x,y;};
struct Point a={10,20};
struct Point *p=&a;

Pointer to record.

Arrow operator

printf(“%d”,p->x);
p->y=25;

The expression p->x accesses the x member of the structure pointed to by p. It is equivalent to (*p).x. Parentheses are necessary in this latter form because the dot operator binds more tightly than unary *.

Expression Meaning
a.x Member of object a
p->x Member through pointer p
(*p).x Equivalent to p->x
&a Address of structure a
*p The pointed-to structure
A claim ticket illustrates identifying an existing record. Illustrative image.

Program: update through a pointer

#include <stdio.h>
struct Point {int x,y;};
int main(void){
struct Point a={10,20};
struct Point *p=&a;
p->x=30;
printf(“%d %d”,a.x,a.y);
return 0;
}

Output: 30 20

Indirect update.

Changing the member through a valid pointer changes the original structure, not a copy. A pointer must refer to a live object before dereferencing it. Access through a null, dangling or otherwise invalid pointer is not permitted. Remember: Object -> dot; pointer -> arrow.

Exam Check

Rewrite p->x without arrow. Answer: (*p).x.

12. Structures and functions

Passing by value

void print(struct Point p){
printf(“%d %d”,p.x,p.y);
}
void change(struct Point p){
p.x=99;
}

The function print receives a copy of the argument’s member values. The change function modifies only its own parameter object, not the caller’s record.

Passing by address

void move(struct Point *p){
p->x+=10;
p->y+=5;
}

The address is itself passed by value, but the callee can use that address to modify the caller’s object.

Original and copy.

When a function should inspect a record without modifying it, a pointer to const structure is useful.

void show(const struct Point *p){
printf(“%d”,p->x);
}

Returning a record

struct Point make(int x,int y){
struct Point r={x,y};
return r;
}
struct Point a=make(4,7);

Method Effect
Value parameter Independent parameter object
Pointer parameter Can alter pointed-to object
Const pointer parameter Read-only through this pointer
Return struct Produces a record value

Program trace

For a Point a={4,7}, move(&a) results in a={14,12}. If change(a) is called instead, a.x remains unchanged in the caller.

Returning the value of a local structure is valid. Returning a pointer to an automatic local structure is not valid for later use, because the object’s lifetime ends when the function returns.

Use pointer parameters for shared access and copies for independent values where appropriate.

Exam Check

How can a function modify the caller’s record? Answer: Receive a pointer to the caller’s object.

13. Self-referential structures

A self-referential structure contains a pointer to the same structure type. It cannot contain a direct complete member of its own type.

struct Node {
int data;
struct Node *next;
};

Node link.

Linking two objects

struct Node b={20,NULL};
struct Node a={10,&b};

The next member stores the address of another Node object. The second object’s next field is null, indicating the end of this small sequence.

Linked records.

This pattern is the basis of linked lists, trees and other linked data structures. The pointer makes the size finite because it stores an address, not a complete recursive object.

Traversing a small link chain

#include <stdio.h>
struct Node{
int data; struct Node *next;
};
int main(void){
struct Node b={20,NULL};
struct Node a={10,&b};
for(struct Node *p=&a;p;
p=p->next){
printf(“%d “,p->data);
}
return 0;
}

Output: 10 20

Key precautions

Both a and b must remain alive during traversal. The loop stops before dereferencing the null pointer. If a sequence contains a cycle, this simple termination condition may never be reached.

In a linked record, each node has its own member storage; the next member creates a relationship between distinct objects. This is different from embedding another complete structure as an ordinary member.

Exam Check

Why is a self-referential pointer allowed? Answer: The pointer has finite size.

14. Introduction to unions

A union is a user-defined aggregate type that allows different members to share storage. Its members are alternative interpretations of the same storage region rather than independent simultaneous values.

union Data {
int i;
float f;
char ch;
};

The tag Data defines the union type. Declare an object using union Data u. Each ordinary member begins at the same address within the object.

Shared storage concept.

The union must be large enough and sufficiently aligned for any of its members. It may contain trailing padding. Its size is at least the size of the largest member, but exact size and alignment depend on the implementation.

Main purpose

Unions represent alternatives compactly, for example a numeric value that can be an integer or floating-point value at different times. A separate tag can record which interpretation is intended.

Interchangeable lenses illustrate alternatives sharing one mount. Illustrative image.

Structure versus union

Property Structure Union
Storage Separate member regions Overlapping regions
Size Members plus possible padding At least largest member
Values All members may hold values Use intended current member
Typical use Record Alternative representation
Syntax struct union

For struct S { int i; float f; }, both members may be used independently. For union U { int i; float f; }, assigning f may replace the representation previously written through i. Memory trick: Structure stores several fields; union uses a shared region. A union does not allocate one complete separate object-sized region for each alternative.

Exam Check

Do union members have separate storage? Answer: No, they overlap.

15. Declaring, initializing and accessing unions

Declaration and initialization

union Value {
int i;
float f;
};
union Value u={25};
union Value v={.f=3.5f};

The positional initializer initializes the first named member. A designated initializer (C99) explicitly selects another member.

printf(“%d”,u.i);
printf(“%.1f”,v.f);

The two independent union objects contain their own representations. Initializing v.f does not affect u.

Updating an alternative

u.i=40;
u.f=2.5f;
printf(“%.1f”,u.f);

Current alternative.

After assigning u.f, the intended stored value is 2.5f. Do not treat u.i as if it still held 40.

Union member operators

An ordinary union object uses the dot operator. A pointer to a union uses the arrow operator.

union Value *p=&u;
p->f=4.0f;
printf(“%.1f”,u.f);

Output: 4.0

Example Meaning
u.i Access integer member
u.f Access floating member
p->f Access through union pointer
&u Address of union object
sizeof u Size of complete union

Reading a member other than the last one written reinterprets the stored object representation in C and may yield a nonportable result or a trap representation. Do not rely on such reads in elementary programs. Track the intended member and access it explicitly.

Exam Check

How do you initialize union member f explicitly? Answer: {.f=3.5f}.

16. Operations on unions

Union assignment between compatible union types is permitted. The value is copied to the destination union object. Like structures, unions may be passed to functions and returned by value.

union Value a={.i=18};
union Value b=a;
printf(“%d”,b.i);

Output: 18

Whole-object and member operations

Operation Permitted?
Assign compatible union Yes
Read intended member Yes
Use sizeof Yes
Take address Yes
Add two unions No
Compare two unions with == No

A member can take part in normal arithmetic or comparison according to its declared type. The overall union object is not a scalar number.

a.i += 5;
printf(“%d”,a.i);

If a.i currently contains 18, it becomes 23.

Worked memory-size problem

union Mix {
char c[8];
int i;
double d;
};

Assume char occupies 1 byte, int 4 bytes, double 8 bytes and that the union is aligned to 8 bytes. Each member starts at offset zero. An implementation may give this union size 8 bytes. Verify using sizeof on the actual system.

Alternative widths.
Member Assumed size
c[8] 8 bytes
i 4 bytes
d 8 bytes
Largest 8 bytes

The sum 20 is not the union size. A structure with the same members would require separate regions and possibly extra padding.

Exam tip: The largest-member rule gives a lower bound; the actual size can include padding to satisfy alignment.

Exam Check

If the largest union member occupies 8 bytes, is 8 a guaranteed total? Answer: No, alignment may require padding.

17. Tagged unions and applications

A tagged union combines a union of alternative values with a separate discriminant describing the intended active member.

enum Kind {INTEGER,REAL};
union Number {
int i; double d;
};
struct NumberValue {
enum Kind kind;
union Number value;
}; struct NumberValue n={
INTEGER,{.i=42}
};

Tagged value.

Before reading the union, test the tag. When changing the alternative, update both the tag and the stored value.

n.kind=REAL;
n.value.d=3.25;

This convention helps readers understand which representation should be used. C does not automatically maintain a union tag; the program must keep it consistent.

A selected indicator tag illustrates a tagged alternative. Illustrative image.

Program: print the selected value

#include <stdio.h>
enum Kind {INTEGER,REAL};
struct Value {
enum Kind kind;
union {int i; double d;} data;
};
void print(struct Value v){
switch(v.kind){
case INTEGER:
printf(“%d”,v.data.i); break;
case REAL:
printf(“%.2f”,v.data.d); break;
}
}
int main(void){
struct Value v={REAL,{.d=3.25}};
print(v);
return 0;
}

Output: 3.25

Possible applications include a menu result carrying alternative data, a token carrying a number or text reference, or a device status with alternative payloads. The tag is separate storage; the union alternatives overlap.

Exam Check

Who keeps the union tag consistent? Answer: The program.

Model different payment amounts with a tagged union

A billing record can carry either an integer number of reward points or a monetary amount. A separate tag identifies how the payload should be interpreted by the display function.

#include <stdio.h>
enum Mode{POINTS,CASH};
struct Payment{
enum Mode mode;
union{int points;double cash;} amount;
};
int main(void){
struct Payment p={POINTS,{.points=90}};
printf(“%d points\n”,p.amount.points);
p.mode=CASH;p.amount.cash=45.50;
if(p.mode==CASH)
printf(“%.2f”,p.amount.cash);
return 0;
}

Output: 90 points, then 45.50 on the next line.

Stage Tag Member to read
Initial POINTS points
After update CASH cash

The tag and union data live in distinct structure members. Therefore the tag is still available when either payload is selected. The union itself provides overlapping storage; the struct maintains the relationship between that storage and its interpretation.

Validity invariant

At every point where a payment record is consumed, the tag must identify the member that contains the intended value. Update the tag and corresponding payload together to preserve this invariant.

18. Enumerated data types

An enumeration defines a type consisting of named integer constants called enumerators. It improves readability when a value represents a finite set of named choices.

enum Day {
MON,TUE,WED,THU,FRI,SAT,SUN
};
enum Day today=WED;

By default, the first enumerator has value 0 and each following value is one greater than the preceding value. In this example WED is 2.

Enumeration values.

Explicit values

enum Status {
OK=0, WAITING=5, FAILED
};

FAILED receives value 6. Enumerator names are constants, not variables. Different enumerator names may have the same numeric value.

enum Level{LOW=1,MEDIUM,HIGH=10};

MEDIUM is 2 and HIGH is 10.

Traffic-light states illustrate named enumeration values. Illustrative image.

Why use enum?

Approach Example
Magic number if(status==2)
Named enumerator if(status==FAILED)
Meaning Named choices easier to understand

Program: menu with enum

#include <stdio.h>
enum Choice {ADD=1,EXIT=2};
int main(void){
enum Choice c=ADD;
switch(c){
case ADD: puts(“Add”); break;
case EXIT: puts(“Exit”); break;
}
return 0;
}

Output: Add An enumerated type is compatible with an implementation-selected integer type. Its object size is not guaranteed to equal sizeof(int). In C, enum variables are not automatically restricted by runtime checks to the listed enumerator values. Validate input before converting or assigning a choice.

Exam Check

What is Z in enum E {X=4,Y,Z}? Answer: 6.

19. Enumeration operations and comparisons

Enumerators can be used in switch cases, array indices where valid, conditions and arithmetic expressions. They are integer constants in conventional C standards such as C17.

enum Traffic {RED,YELLOW,GREEN};
enum Traffic signal=GREEN;
if(signal==GREEN) puts(“Go”);

Traffic states.

enum and typedef

typedef enum {
OFF, ON
} Power;
Power state=ON;

The alias Power simplifies declarations without changing the enumerator names. State variables make programs more expressive than unlabelled integer flags.

Form Meaning
enum Level l Declare enum object
LOW=1 Explicit enumerator value
case LOW: Named case label
typedef enum … Alias for type

Worked output prediction

enum Code {A=2,B,C=8,D};
printf(“%d %d %d %d”,A,B,C,D);

Output: 2 3 8 9.

Enumerator Rule Value
A Explicit 2
B Previous + 1 3
C Explicit 8
D Previous + 1 9

enum versus #define

Feature enum Preprocessor macro
Purpose Related named integer choices Text substitution
Type Introduces enum type No type of its own
Grouping Declared together Separate directives
Compiler awareness Enumerators are identifiers Expanded before compilation

Prefer an enum when representing a finite group of related integral states, especially in switch-based logic. Use descriptive enumerator names to reduce collisions in larger programs.

Exam Check

Why use enumerators instead of magic numbers? Answer: Named states communicate meaning.

20. Introduction to storage classes

A storage class specifier helps describe the storage duration, linkage or declaration behavior of an identifier. These are related but distinct concepts.

Scope, lifetime and linkage

Scope: The region of program text in which a declaration’s name can be used.

Storage duration: The period during execution for which an object’s storage exists.

Linkage: Whether declarations of a name denote the same entity across scopes or translation units.

Three concepts.
Storage class Typical meaning
auto Automatic local object
register Automatic local object with hint
static Persistent object or internal linkage
extern Declare externally linked entity

These four storage classes are explicitly included in the Unit IV syllabus. Other C specifiers are beyond the required list.

A counter and stopwatch illustrate persistent and temporary values. Illustrative image.

Scope is not lifetime

A block-scope static object is visible only within its block but exists throughout the execution of the program. A file-scope object can have either internal or external linkage and static storage duration.

Example Scope Storage duration
int x inside function Block Automatic
static int x inside function Block Static
int g at file scope File Static
static int g at file scope File Static

Think before selecting

Ask three questions: Who needs to see the name? How long must the object’s value persist? Should declarations in different source files refer to the same entity? Answering these separately prevents confusion about static and extern.

The storage class does not determine the amount of memory alone; the object’s type and implementation determine size and alignment.

Exam Check

Can a name have block scope but static storage duration? Answer: Yes, a static local object.

21. Automatic storage class

The auto storage-class specifier explicitly denotes an automatic object declared at block scope. Ordinary local variables without a storage-class specifier normally have automatic storage duration.

void demo(void){
auto int x=10;
int y=20;
printf(“%d %d”,x,y);
}

Both x and y have automatic storage duration. Their storage is associated with execution of the enclosing block. Their names have block scope and generally no linkage.

Automatic variable lifecycle.

Initialization rules

An automatic arithmetic local variable without an initializer has an indeterminate value. Do not read it before assigning a valid value.

int count;
count=0;
count++;

This is valid because count is assigned before it is read.

Program trace

#include <stdio.h>
void show(void){
auto int count=0;
++count;
printf(“%d “,count);
}
int main(void){
show(); show(); show();
return 0;
}

Output: 1 1 1

Call Initial value Printed
1 0 1
2 0 1
3 0 1

Each call creates and initializes a new automatic count object. It does not preserve its previous call’s value. The compiler may optimize away physical storage when the language’s observable behavior is preserved. Use: Temporary counters, loop variables, intermediate calculations and function-local working data. Automatic objects are the usual choice when persistence is unnecessary.

Exam Check

What is the default initial value of an uninitialized automatic int? Answer: Indeterminate; assign before reading.

22. Register storage class

The register storage-class specifier declares an automatic local object and historically suggests frequent access, such as a loop counter. The implementation may ignore the optimization hint.

register int i;
for(i=0;i<5;i++)
printf(“%d “,i);

Output: 0 1 2 3 4

Loop counter values.

The value need not actually be stored in a hardware register. Modern compilers often allocate registers automatically as part of optimization.

Important address rule

In conventional C through C17, unary & cannot be applied to a register object. Avoid using this storage class when a pointer to the declared object must be taken.

Comparison with auto

Feature auto register
Scope Block Block
Duration Automatic Automatic
Linkage None None
Default value without initializer Indeterminate Indeterminate
Address operator Allowed for ordinary objects Not allowed under C17

Program

#include <stdio.h>
int main(void){
register int i;
int sum=0;
for(i=1;i<=5;i++) sum+=i;
printf(“%d”,sum);
return 0;
}

Output: 15

Exam tip: Register is a request, not a guarantee of faster execution. The actual register allocation is controlled by the compiler and target architecture.

Exam Check

Does register guarantee a hardware register? Answer: No.

23. Static local variables

A block-scope object declared static has static storage duration. It exists throughout program execution even though its name is visible only within its block.

void counter(void){
static int n=0;
++n;
printf(“%d “,n);
}

Static counter across calls.

The initializer is not executed anew each time the function is entered. The same object retains its value between calls.

Default initialization

If a static arithmetic object has no explicit initializer, it is initialized to zero. Pointer objects are initialized to null pointers and aggregates recursively receive the appropriate initial values.

static int total;

This differs from an uninitialized automatic int, whose value is indeterminate.

Program: static counter

#include <stdio.h>
void count(void){
static int n;
printf(“%d “,++n);
}
int main(void){
count(); count(); count();
return 0;
}

Output: 1 2 3

Call Before increment After
1 0 1
2 1 2
3 2 3

Use cases

Use a static local object to retain a function’s state between invocations, for example the number of calls or an accumulated total. Avoid static state when independent instances are required. In multithreaded programs, shared mutable static state may require synchronization. The name n still has block scope. It is not accessible from main just because it exists for the entire execution.

Exam Check

What does a static local variable do between calls? Answer: It retains its stored value.

24. Static file-scope declarations

At file scope, static restricts the linkage of an object or function name to internal linkage. Such a name denotes an entity within the same translation unit, rather than serving as an externally linked name.

static int total=0;
static void add(int n){
total+=n;
}

File private state.

The object total has static storage duration regardless of the static keyword because it is declared at file scope. The keyword changes its linkage here.

Two different uses of static

Placement Effect
Inside a function Persistent object with block scope
File-scope object Internal linkage and static duration
File-scope function Internal linkage for function name

Functions themselves are not objects with an object storage duration. static on a function declaration controls linkage.

Example: internal helper

#include <stdio.h>
static int sum=0;
static void update(int x){
sum+=x;
}
int main(void){
update(5); update(7);
printf(“%d”,sum);
return 0;
}

Output: 12

Keeping an implementation helper private to its translation unit reduces name conflicts and accidental dependencies between source files.

Translation unit: A source file after preprocessing, including the headers introduced by #include.

Remember that static does not mean constant. A static int may be modified throughout program execution unless it is declared const or is otherwise non-modifiable.

Exam Check

What does file-scope static control? Answer: Internal linkage.

25. External storage class

The extern storage-class specifier commonly declares an object or function with linkage so that it can be referred to from another translation unit. A declaration such as extern int total; ordinarily does not define storage for the object.

/* declaration */
extern int total;

One translation unit must provide the definition when the object is used.

/* definition in one file */
int total=10;

Shared definition.

At file scope, a non-static ordinary object definition generally has external linkage. It has static storage duration; it exists throughout program execution.

An extern declaration with an initializer at file scope is itself a definition. Do not place an initialized definition in several files.

Two-file example

/* data.c */
int total=10;
void add(void){total+=5;}

/* main.c */
#include <stdio.h>
extern int total;
void add(void);
int main(void){
add();
printf(“%d”,total);
return 0;
}

Output: 15 when both source files are compiled and linked into one program.

File Role
data.c Defines total and add
main.c Declares total and calls add
Linking Resolves external references

Declarations across files must use compatible types. A common practice is to put an extern declaration in a header, then include that header in relevant source files, with a single corresponding definition in one source file.

Exam Check

Where is storage supplied for an extern declaration? Answer: At the object’s definition.

26. Storage-class comparison and scope tracing

Specifier Scope Duration
auto Block Automatic
register Block Automatic
static local Block Static
static file File Static
extern file File Static for object
Form Linkage Default initialization
auto int x None Indeterminate
register int x None Indeterminate
static local None Zero
static file Internal Zero
extern object Usually external At definition

Worked scope example

int x=5;
void f(void){
int x=10;
printf(“%d”,x);
}

The local declaration hides the file-scope x within the block. The function prints 10. The file-scope x still exists and remains 5.

Name shadowing.

Do not confuse shadowing with modification. They are different objects.

Objective-style trace

#include <stdio.h>
int g=4;
void demo(void){
int a=0;
static int b=0;
++a; ++b; ++g;
printf(“%d %d %d\n”,a,b,g);
}
int main(void){
demo(); demo(); demo();
return 0;
}

Call a b g
1 1 1 5
2 1 2 6
3 1 3 7

The automatic a restarts at 0, static local b retains its value, and global g persists. This distinction is frequently tested in output prediction.

Exam memory trick: Auto resets, register hints, static retains locally or hides a file-level name, extern links declarations to a shared definition.

Exam Check

Why do scope and duration differ? Answer: Scope governs name visibility; duration governs object existence.

Combined scope and linkage practice

Study a file-level variable, a shadowing local variable, and a persistent local variable in one small program.

#include <stdio.h>
static int g=10;
void f(void){
int g=2;
static int calls=0;
++g;++calls;
printf(“%d %d\n”,g,calls);
}
int main(void){
f();f();
printf(“%d”,g);
return 0;
}

Output: 3 1 on the first line, 3 2 on the second line, then 10.

Identifier Duration Effect
File g Static Remains 10
Local g Automatic Reinitialized to 2
calls Static Retains count

The local g shadows the file-scoped g. It is incremented independently during each invocation. calls has block scope but static duration, so it preserves its previous value. File-level g has internal linkage because of static.

Diagnose a declaration mistake

If a header contains int counter=0; and two source files include it, both translation units can supply an external definition of counter. Use extern int counter; in the header and place the initialized definition in exactly one source file. This keeps the declaration compatible across translation units without creating multiple definitions.

27. Integrated structure, union and enum example

Problem statement

Represent a product with an identifier, a category and either an integer stock count or a floating-point weight. Use a tag to distinguish the alternate payloads and a structure to group the record.

enum Kind{COUNT, WEIGHT};
union Quantity {
int count;
double kg;
};
struct Product {
int id;
enum Kind kind;
union Quantity q;
};

Product record.

The structure stores all three fields, while q shares storage between count and kg. The enum indicates which ordinary union member should be used.

struct Product p={
101,COUNT,{.count=25}
};

Program fragment: display product

void show(const struct Product *p){
printf(“ID %d: “,p->id);
if(p->kind==COUNT)
printf(“%d items”,p->q.count);
else if(p->kind==WEIGHT)
printf(“%.2f kg”,p->q.kg);
else
puts(“Invalid category”);
}

Call show(&p). The output for the initialized record is ID 101: 25 items. When changing to WEIGHT, set p.kind and p.q.kg together.

Alternate record.

Design reasoning

Use a struct for several fields that exist together, a union for alternatives, an enum for named alternatives and a pointer parameter for inspecting an existing record. Together they model real data in a clear and compact manner.

This example also demonstrates nested member access through p->q.count.

Exam Check

What indicates a tagged union’s selected field? Answer: A separate tag.

28. Solved examination problems

Problem 1: structure size

Assume char=1 byte, int=4 bytes with alignment 4. Find a possible size of struct { char c; int i; }. Solution: c occupies offset 0; offsets 1-3 are padding; i uses offsets 4-7. Total is 8 bytes on this assumed layout.

Structure byte layout.

Problem 2: union size

Assume the program uses union { char c; int i; double d; }, with double size and alignment 8. The size is typically 8 bytes under these assumptions, as all ordinary members start at offset zero.

Type Example size (assumed)
struct char + int 8
union char int double 8

Problem 3: enum values

enum E{P=5,Q,R=12,S};

P=5, Q=6, R=12, S=13.

Problem 4: structure copy

struct P {int x,y;};
struct P a={2,3};
struct P b=a;
b.x=9;

Answer: a.x=2 and b.x=9. Each record has its own integer member.

Problem 5: pointer expression

struct P a={2,3};
struct P *p=&a;
p->y+=4;

Answer: a.y is 7. The pointer accesses the original object.

Problem 6: static output

void f(void){
static int x=10;
x+=2; printf(“%d “,x);
}

Three calls print 12 14 16. Initialization occurs once and subsequent calls retain the stored value.

Concept Key rule
Copy Separate scalar members
Pointer update Original member changes
Static local Persistent storage
Enum sequence Previous enumerator + 1

Exam Check

When calculating structure size, state assumptions and account for alignment.

Additional worked program: nested record report

Represent an appointment with a reference number and a nested date. The example accesses two fields of the embedded date and prints a simple report.

#include <stdio.h>
struct Date{int d,m,y;};
struct Appointment{
int id;struct Date day;
};
int main(void){
struct Appointment a={7,{12,8,2026}};
printf(“%d: %d/%d/%d”,a.id,
a.day.d,a.day.m,a.day.y);
return 0;
}

Output: 7: 12/8/2026. Access to the inner fields requires two member selections, first day and then d, m or y.

Program: filter a record collection

#include <stdio.h>
struct Product{int id;int stock;};
int main(void){
struct Product p[]={{11,8},{12,0},
{13,5}};
int available=0;
for(int i=0;i<3;i++){
if(p[i].stock>0){
printf(“%d “,p[i].id);
available++;
}
}
printf(“| %d”,available);
return 0;
}

Output: 11 13 | 2. The filtering loop does not move or change any product records. It selects records based on one member and reports a count.

Record Stock Selected
11 8 Yes
12 0 No
13 5 Yes

Practice: model an alternative quantity

A record may contain a product id and either weight or unit count. Use an enum for the kind, a union for the alternatives and a struct for their combination. When the kind is changed, assign the matching member before presenting the record. This makes the intended interpretation explicit.

EXAM QUESTIONS WITH ANSWERS

Practice questions covering the definitions, comparisons and applications in Unit IV.

Short-answer practice

Q1. Define a structure in C.

Answer. A structure is an aggregate type that groups related named members, potentially with different declared types, into a single record object.

Q2. How is a structure type defined?

Answer. Use struct followed by an optional tag and a member declaration list in braces. The definition ends with a semicolon; declare objects separately or with it.

Q3. How is a structure initialized?

Answer. Supply member values in declaration order inside braces, or use designated initializers to identify members explicitly, such as .roll=12.

Q4. What is the dot operator used for?

Answer. The dot operator selects a named member of a structure or union object. For a Student object s, s.roll selects its roll member.

Q5. Can a character array member be assigned a literal?

Answer. Not by ordinary array assignment after declaration. Initialize the member at declaration or copy the string into its writable array with sufficient space.

Q6. Which whole-structure operations are allowed?

Answer. Compatible assignment, initialization, passing by value, returning a value, sizeof and taking the address are allowed. Whole-record arithmetic and == are not supplied.

Q7. What is structure padding?

Answer. Padding is space an implementation may insert between members or after the last member to satisfy alignment requirements. Actual size can exceed the sum of member sizes.

Q8. What is a nested structure?

Answer. A complete structure type used as a member of another structure. It can represent related subfields, such as a date within a student record.

Q9. How is an array of structures accessed?

Answer. Use an index to select a complete record and a dot to select its member. For example, records[2].marks accesses the third student’s marks.

Q10. What is a structure pointer?

Answer. A pointer with an appropriate structure type that refers to a valid record object. It permits indirect access to that object’s members.

Q11. Explain the arrow operator.

Answer. p->member selects the member of the object referenced by p. It is equivalent to (*p).member when p is a valid compatible pointer.

Q12. How can a function modify a caller’s record?

Answer. Receive the address of that record in a structure-pointer parameter and modify the appropriate member through the pointer. Passing the record by value only copies it.

Q13. What is a self-referential structure?

Answer. A record containing a pointer to its own structure type. The pointer has finite size and can refer to another record of the same type.

Q14. Define a union.

Answer. A union is an aggregate type whose ordinary members share the same storage. Different members describe alternative uses of the region.

Q15. How is a union’s size determined?

Answer. It must accommodate its largest member and satisfy applicable alignment requirements. Its exact size may include padding and is obtained with sizeof.

Q16. How can a union be initialized?

Answer. A positional initializer selects the first named member; a designated initializer can select another member, such as union Value u={.f=2.5f}.

Q17. What is a tagged union?

Answer. A union paired with a separate discriminant, often an enumeration, that identifies the intended stored alternative. The program maintains the tag and payload consistently.

Q18. What is an enumerated type?

Answer. An enum introduces named integer constants for related alternatives, improving clarity when representing finite choices such as menu states or status values.

Q19. How are default enumerator values assigned?

Answer. The first unassigned enumerator receives zero, and each subsequent unassigned value is one greater than the preceding enumerator. Explicit values can override the sequence.

Q20. What is scope?

Answer. The region of source text in which a declared name is visible. Scope differs from storage duration, which concerns an object’s lifetime during execution.

Q21. Describe automatic storage class.

Answer. An ordinary block-local object typically has automatic storage duration. auto can state this explicitly; its uninitialized arithmetic value is indeterminate.

Q22. What is register storage class?

Answer. A block-local automatic declaration historically suggesting frequent access. The compiler may ignore the hint; in C17 the address operator cannot be applied to such an object.

Q23. What does static mean inside a function?

Answer. A static local object persists throughout program execution, retaining its value across calls while its name remains visible only within its block.

Q24. What is the purpose of extern?

Answer. It commonly declares a linked entity whose definition is provided elsewhere. A corresponding compatible definition supplies the object when it is used.

Structured long-answer practice

Use a clear definition, numbered explanation, examples and relevant comparisons. Adjust the depth of your answer to the marks and question.

Long question 1. Explain structure definition, declaration, initialization and member access.

Answer

  • 1. Definition. A structure type groups several named fields into one record. For struct Student {int roll; char name[20]; float marks;};, the fields have different data types and serve distinct purposes.

  • 2. Object declaration. The tag describes a type but does not by itself create storage for a record. struct Student s; creates an object whose members can hold student data.

  • 3. Initialization. Use an ordered brace list such as {12,”Asha”,80.0f}. Designated initialization can select a field explicitly, improving readability and reducing dependence on field order.

  • 4. Member access. Select a member using the dot operator, such as s.marks. Numeric members can be modified with arithmetic assignments; character arrays require suitable initialization or copying.

  • 5. Application. A student information system can keep identification and grades associated in one object. Choose adequate field capacities, validate values and avoid accessing uninitialized automatic members.

Long question 2. Explain structure operations, nested structures and arrays of structures.

Answer

  • 1. Record assignment. An assignment between compatible structure types copies member values, including array members. Arithmetic and direct equality comparisons between whole structures are not standard C operations.

  • 2. Individual operations. Update and compare members using operations appropriate to their own declared types. Compare strings by their contents. For checking record equality, compare the relevant members separately.

  • 3. Nested records. A member can have a complete structure type, such as struct Date inside struct Student. Access the year through a chain of member selections such as s.dob.y.

  • 4. Record collections. An array struct Student a[10]; stores ten complete records. Select a[i] to identify one student and a[i].roll or a[i].marks to select a field.

  • 5. Layout and use. Members occupy storage in declaration order with possible alignment padding. Array elements have a stride equal to the complete record size. When sorting records, exchange whole records to preserve field associations.

Long question 3. Discuss pointers to structures and their use with functions.

Answer

  • 1. Declaration. Given a record object struct Point a={2,3};, declare struct Point *p=&a; to refer to it. The record object must remain alive during indirect access.

  • 2. Member selection. Use p->x to select a member of the referenced object. Parenthesized (*p).x has the same meaning. The dot is used when the operand is the object itself.

  • 3. Indirect modification. An assignment p->x=10 changes the member in the original record. A second pointer to the same object can observe that updated value.

  • 4. Function interfaces. A parameter declared struct Point *p permits modifications to the caller’s record. A value parameter receives independent copied member values; a pointer to const can express read-only access.

  • 5. Linked structures. A self-referential record can store a pointer to another object of its own type, as in struct Node *next. Such relationships support linked data representations; validate references before traversal.

Long question 4. Explain union declaration, memory layout, operations and applications.

Answer

  • 1. Meaning. A union provides alternative member interpretations of one shared region. union Value {int i; float f;}; describes overlapping ordinary members rather than two independent simultaneous fields.

  • 2. Declaration and initialization. Declare union Value u; and initialize one member, either through the first-member initializer or a designator such as {.f=3.5f}. Dot selects a member of an object; arrow selects through a pointer.

  • 3. Memory layout. All ordinary union members start at the same address. Storage must satisfy the size and alignment of all alternatives. sizeof reports the total region, including any padding.

  • 4. Operations. Compatible union assignment, passing a union value and reading its intended member are allowed. After storing a new alternative, do not assume the previous member still represents its old value.

  • 5. Applications. A separate enum tag can identify which payload is meaningful in a tagged record. A union is suitable for alternative data, while a structure groups fields needed together.

Long question 5. Describe enumerated data types and distinguish them from symbolic macros.

Answer

  • 1. Definition. An enumeration introduces an integral type and named constants representing choices. For enum Signal {RED,YELLOW,GREEN};, the names clarify the meaning of a signal state.

  • 2. Value assignment. The first default enumerator receives zero. Following unspecified enumerators increase by one from the previous value. With enum E{A=4,B,C=9,D};, B is 5 and D is 10.

  • 3. Declarations and use. Declare enum Signal s=GREEN; or an alias using typedef. Enumerators can appear in conditions and switch labels, eliminating unclear numeric codes.

  • 4. Representation. The compatible integer type and storage size are implementation-dependent. C does not automatically enforce a runtime restriction to the named enumerators; check external input.

  • 5. Comparison. An enum groups related names within a language declaration. A #define macro is substituted by the preprocessor and does not itself introduce an enumerated type. Use enums for collections of named integral choices.

Long question 6. Explain automatic, register, static and external storage classes.

Answer

  • 1. Underlying concepts. Scope determines where a name is visible, storage duration determines how long an object exists, and linkage determines whether declarations can identify the same entity.

  • 2. Automatic. A normal block-local object usually has automatic duration. It is created for block execution; without an initializer its arithmetic value is indeterminate. auto makes this storage-class choice explicit.

  • 3. Register. register also denotes an automatic object and historically requests fast access. Actual allocation is a compiler choice. Under C17, the unary address operator is not allowed on a register object.

  • 4. Static. A static local object is initialized once and retains its value across invocations. At file scope, static gives a name internal linkage; a file-level static object exists throughout the program.

  • 5. External. extern commonly declares an externally linked object defined in another translation unit. One compatible definition provides storage. Separate visible declarations from the definition to avoid multiple-definition problems.

QUICK REVISION AND KEY TERMS

Concept Recall
struct Separate named fields
union Overlapping alternatives
enum Named integer choices
. Object member selection
-> Pointer member selection
typedef Type alias
sizeof Object size
offsetof Member byte offset

Storage classes at a glance

Class Duration and linkage
auto Automatic block object
register Automatic, optimization hint
static local Persistent, block scope
static file Internal linkage
extern Declares linked entity

Important syntax

struct Point {int x,y;};
struct Point a={2,3};
struct Point *p=&a;
p->x=10;
union Value {int i;float f;};
enum State {OFF,ON};

Remember: A structure contains fields used together. A union stores an alternative representation. A tag identifies the intended union member.

Output-prediction practice

enum Result{FAIL=0,PASS=5,MERIT};
printf(“%d”,MERIT);

Output: 6.

struct P{int n;char code[4];};
struct P a={12,”XYZ”},b=a;
b.code[0]=’Q’;
printf(“%s %s”,a.code,b.code);

Output: XYZ QYZ. Structure assignment copies array members to independent storage.

Memory numerical

Assume char alignment 1, int alignment 4 and double alignment 8. struct {char c; int i;} may occupy 8 bytes. A union of char, int and double may occupy 8 bytes. Confirm actual size using sizeof.

Common mistakes

Mistake Correct approach
Whole record equality with == Compare members
Arrow on object Use dot
Writing a different union member Track selected alternative
Static means constant Static relates to duration or linkage
Extern always defines storage Separate declaration and definition

Practice yourself

Define a nested Date and Student record; calculate a class average from an array of records; write a tagged union representing two payment options; trace automatic and static counters.

Final checklist: State member types, memory-layout assumptions, validity of references, enum values, scope, duration and linkage.

Exclusive Student Alerts

Join AKTU VIP Telegram & WhatsApp Group

Get immediate exam updates, syllabus changes, quantum PDFs, and viva questions.

Have Questions or Want to Discuss?

Join the community conversation or ask your queries in the comments.

View Comments & Discussion →
Home Notes Syllabus PYQs Quantum