How unit 4 is examined
This unit covers structures, the preprocessor and unions; the marks sit in structure versus union, the preprocessor's features, and an array-of-structures program.
Structure: Why use structure
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A structure is a user-defined data type that groups variables of different types under one name.</mark>
Key points.
- An array holds items of one type only, whereas a structure can hold an int, a float and a string together.
- It lets related data such as a student's roll number, name and marks be treated as one record.
- It makes programs cleaner because one variable is passed or copied instead of many.
Declaration of structure
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A structure is declared with the keyword struct, a tag name and a list of members in braces ending with a semicolon.</mark>
Key points.
- Declaring the structure only creates a new type and reserves no memory.
- Memory is allocated when a variable is defined, for example
struct Student s1;(in C++ the word struct may be dropped). - Variables can also be defined right after the closing brace, and members may be initialised with
{101, "Ravi", 78.5}.
struct Student { int roll; char name[20]; float marks; };
Student s1 = {101, "Ravi", 78.5};
Accessing structure elements
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A structure member is accessed with the dot operator as variable.member, and through a pointer with the arrow operator as ptr->member.</mark>
Key points.
s1.roll = 5;assigns to a member andcout << s1.marks;reads it.- With
Student *p = &s1;the member is reached asp->roll, which equals(*p).roll. - Whole structures of the same type can be assigned with
s2 = s1;, which copies every member.
How structure elements are stored
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>The members of a structure are stored in contiguous memory in the order of declaration, and the compiler may add padding bytes for alignment.</mark>
Key points.
- The size of a structure is at least the sum of its members' sizes.
- Padding is inserted so that each member starts at an address that suits its type, so
struct { char c; int i; }occupies 8 bytes, not 5, on a machine with 4-byte int. - The size is obtained with
sizeof.
Array of structure
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>
Definition. <mark>An array of structures is an array in which every element is a structure, used to store many records of the same type.</mark>
Key points.
- It is declared as
Fruit f[4];and element i is used asf[i].name. - A loop is used to read and print all the records.
- The elements are stored one after another in memory.
#include <iostream>
using namespace std;
struct Fruit { char name[20]; char type[20]; char color[20]; };
int main() {
Fruit f[4];
for (int i = 0; i < 4; i++) cin >> f[i].name >> f[i].type >> f[i].color;
for (int i = 0; i < 4; i++)
cout << f[i].name << " " << f[i].type << " " << f[i].color << endl;
}
// Input: Apple Pome Red ... Output: Apple Pome Red (one line per fruit)
Asked: [7 marks] (Jun 2020) Define a structure that represents Fruit with properties fruit name, fruit type, fruit color. Write a program that accepts data of four fruits and displays the results.
Uses of structure
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Structures are used wherever different data items describe one entity and must be handled together.</mark>
Key points.
- They store records such as student, employee or book details.
- They are passed to and returned from functions as one unit.
- Combined with pointers they build linked lists and trees, and they are the basis of classes in C++.
Preprocessor: features of Preprocessor
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>
Definition. <mark>The preprocessor is a program that processes the source code before compilation, acting on lines that begin with #, called directives.</mark>
Key points.
- File inclusion with
#includecopies the contents of a header file into the program, for example#include <iostream>. - Macro substitution with
#definereplaces a name by text, for example#define PI 3.14. - Conditional compilation with
#if,#ifdef,#elseand#endifcompiles a part of the code only when a condition holds. - Other directives such as
#undefand#pragmaremove a macro or give compiler-specific instructions. - A directive needs no semicolon and normally occupies one line.
Asked: [7 marks] (Jun 2020) What do you mean by Preprocessor? Explain features of preprocessor.
Macro expansion
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A macro is a name defined by #define that the preprocessor replaces with its text wherever it appears, which is called macro expansion.</mark>
Key points.
#define MAX 100replaces every MAX in the code by 100 before compilation.- It is plain text substitution, so no memory is used and no type checking is done.
- Macro names are written in capital letters by convention, and they are not replaced inside string literals.
Macros with arguments
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A macro with arguments is a function-like macro whose parameters are replaced by the actual arguments during expansion.</mark>
Key points.
#define SQR(x) ((x)*(x))expandsSQR(3+1)to((3+1)*(3+1)), which is 16.- It is faster than a function because there is no call overhead, but the code grows at every use.
- Without brackets
#define SQR(x) x*xgives3+1*3+1 = 7, which is a wrong answer.
File inclusion
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>The #include directive inserts the contents of another file into the source before compilation.</mark>
Key points.
#include <file>searches the standard system directories and is used for library headers.#include "file"searches the current directory first and is used for the programmer's own headers.- Including a header gives access to the declarations of functions and classes it contains.
Conditional compilation
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Conditional compilation includes or skips blocks of code depending on a condition evaluated by the preprocessor.</mark>
Key points.
#if,#elif,#elseand#endiftest a constant expression, and#ifdefand#ifndeftest whether a macro is defined.- Only the selected block reaches the compiler.
- It is used for platform-specific code, debugging code, and header guards.
#define VER 2
#if VER == 1
puts("one");
#elif VER == 2
puts("two"); // compiled
#endif
Miscellaneous directives
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Preprocessor directives such as #include, #define, #undef and #pragma control the source text before compilation.</mark>
Key points.
#includeinserts a file and#definecreates a macro.#undef NAMEremoves a macro definition so the name can be redefined.#pragmagives a compiler-specific instruction, for example#pragma onceto include a header only once.#errorstops compilation with a message.
Union: Union definition and declaration
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>
Definition. <mark>A union is a user-defined type declared with the keyword union in which all members share the same memory location, so its size equals that of its largest member.</mark>
Key points.
- Only one member holds a valid value at a time, because writing one member overwrites the others.
- A structure gives each member its own memory, so its size is the sum of the members (plus padding).
- All union members start at the same address.
| Basis | Structure | Union |
|---|---|---|
| Keyword | struct | union |
| Memory | Separate for each member | Shared by all members |
| Size | Sum of members (with padding) | Size of the largest member |
| Values | All members hold values together | Only one member holds a value at a time |
| Access | Any member at any time | Only the last-written member is meaningful |
| Use | Records with many fields | Saving memory when one of several values is needed |
<figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u4-01" viewBox="0 0 338 80" width="338" height="80" role="img" aria-label="struct S {int i; double d;} takes 4+8 bytes plus padding (16); union U {int i; double d;} takes 8 bytes shared"><style>#dsfig-u4-01 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u4-01 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u4-01 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u4-01 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u4-01 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u4-01 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u4-01 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u4-01 .t{fill:#16181D;font-weight:500}#dsfig-u4-01 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u4-01 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u4-01 .dot{fill:#16181D}#dsfig-u4-01 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u4-01 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u4-01 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u4-01 .ah{fill:#454C5A}#dsfig-u4-01 .ah.hi{fill:#2340B8}#dsfig-u4-01 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u4-01 .wl .t{font-size:12px;font-weight:700}#dsfig-u4-01 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u4-01 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u4-01 .e{stroke:#B1B7C3}html.dark #dsfig-u4-01 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u4-01 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u4-01 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u4-01 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u4-01 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u4-01 .t{fill:#E6E8ED}html.dark #dsfig-u4-01 .t.inv{fill:#0F1115}html.dark #dsfig-u4-01 .kd{stroke:#E6E8ED}html.dark #dsfig-u4-01 .dot{fill:#E6E8ED}html.dark #dsfig-u4-01 .ann{fill:#8FA3FF}html.dark #dsfig-u4-01 .lbl{fill:#858D9C}html.dark #dsfig-u4-01 .ptr{fill:#8FA3FF}html.dark #dsfig-u4-01 .ah{fill:#B1B7C3}html.dark #dsfig-u4-01 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u4-01 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u4-01 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u4-01 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><path class="e" d="M59,40 L277,40" marker-end="url(#ah1)"/><circle class="n" cx="40" cy="40" r="18"/><text class="t" x="40" y="40" dy=".35em" text-anchor="middle">S</text><circle class="n" cx="298" cy="40" r="18"/><text class="t" x="298" y="40" dy=".35em" text-anchor="middle">U</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">struct S {int i; double d;} takes 4+8 bytes plus padding (16); union U {int i; double d;} takes 8 bytes shared</figcaption></figure>
struct S { int i; double d; }; // sizeof = 16
union U { int i; double d; }; // sizeof = 8
S s = {1, 2.5}; // both members stored
U u; u.i = 1; // u.d now shares the same bytes
Asked: [7 marks] (Jun 2020) Difference between Structure and Union. Explain with example.
Accessing a union member
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Union members are accessed with the dot operator, or the arrow operator through a pointer, exactly like structure members.</mark>
Key points.
- Only the member most recently written gives a meaningful value.
- After
u.i = 65;readingu.creturns'A'because both share the same byte. - Reading a member other than the last one written gives an unreliable value.
Union of structures
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A union of structures is a union whose members are structures, so the structures share one memory block.</mark>
Key points.
- The size equals that of the largest structure inside it.
- A structure may in turn contain a union, which is common for a record with alternative fields.
- Members are reached by chaining dots, for example
u.s1.x.
Initialization of union member
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Only the first member of a union can be initialised at the time of declaration.</mark>
Key points.
union U u = {10};sets the first member.- Other members are given values by assignment, such as
u.d = 2.5;. - A new assignment overwrites the previous value.
Uses of union
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Unions are used where one memory area must hold different types at different times.</mark>
Key points.
- They save memory in embedded systems and in records with alternative fields.
- They let the same bytes be seen as different types, for example a word as its separate bytes.
- They are used in compilers and device registers to hold values of varying type.
Use of user defined data types
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>User-defined data types are types made by the programmer, using struct, union, enum and typedef.</mark>
Key points.
typedef unsigned int uint;gives an existing type a new name.enum Color {RED, GREEN, BLUE};defines named integer constants starting from 0.- These types make programs readable and self-documenting.
Last-minute revision
- A structure groups different types; members are accessed by
.and through pointers by->. - Declaring a structure reserves no memory; defining a variable does.
- Structure size is the sum of member sizes plus padding, for example
{char; int}is 8 bytes. - An array of structures stores many records:
Fruit f[4]; f[i].name. - The preprocessor runs before compilation and handles lines starting with #.
- Features: file inclusion, macro substitution, conditional compilation.
SQR(3+1)is 16 with brackets and 7 without.<file>searches system directories;"file"searches the current directory first.#undefremoves a macro;#pragmais compiler specific.- A union shares memory, so its size is the largest member; struct size is the sum.
- Only the first union member can be initialised in the declaration.
Memory hooks
- Struct = separate flats, union = one room shared by tenants.
- Preprocessor: hash lines run first, compiler comes second.
- Macro = search and replace, so bracket every argument.
- Struct sums, union maxes.
Coverage checklist
- Structure: Why use structure: no past question.
- declaration of structure: no past question.
- accessing structure elements: no past question.
- how structure elements are stored: no past question.
- array of structure: Fruit program (Jun 2020).
- uses of structure: no past question.
- Preprocessor: features of Preprocessor: preprocessor and its features (Jun 2020).
- macro expansion: no past question.
- micro with arguments: no past question.
- file inclusion: no past question.
- conditional, #if, #elif: no past question.
- miscellaneous directives, #include, #define, directives, #undef, #pragma directives: no past question.
- Union: Union definition & declaration: structure versus union (Jun 2020).
- accessing a union member: no past question.
- union of structures: no past question.
- initialization of union member: no past question.
- uses of union: no past question.
- use of user defined data types: no past question.