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
Not asked since 2022
Definition. A structure is a user-defined data type that groups variables of different types under one name.
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
Not asked since 2022
Definition. A structure is declared with the keyword struct, a tag name and a list of members in braces ending with a semicolon.
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
Not asked since 2022
Definition. A structure member is accessed with the dot operator as variable.member, and through a pointer with the arrow operator as ptr->member.
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
Not asked since 2022
Definition. The members of a structure are stored in contiguous memory in the order of declaration, and the compiler may add padding bytes for alignment.
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
Low weight
Definition. An array of structures is an array in which every element is a structure, used to store many records of the same type.
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
Not asked since 2022
Definition. Structures are used wherever different data items describe one entity and must be handled together.
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
Low weight
Definition. The preprocessor is a program that processes the source code before compilation, acting on lines that begin with #, called directives.
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
Not asked since 2022
Definition. A macro is a name defined by #define that the preprocessor replaces with its text wherever it appears, which is called macro expansion.
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
Not asked since 2022
Definition. A macro with arguments is a function-like macro whose parameters are replaced by the actual arguments during expansion.
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
Not asked since 2022
Definition. The #include directive inserts the contents of another file into the source before compilation.
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
Not asked since 2022
Definition. Conditional compilation includes or skips blocks of code depending on a condition evaluated by the preprocessor.
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
Not asked since 2022
Definition. Preprocessor directives such as #include, #define, #undef and #pragma control the source text before compilation.
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
Low weight
Definition. 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.
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 |
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
Not asked since 2022
Definition. Union members are accessed with the dot operator, or the arrow operator through a pointer, exactly like structure members.
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
Not asked since 2022
Definition. A union of structures is a union whose members are structures, so the structures share one memory block.
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
Not asked since 2022
Definition. Only the first member of a union can be initialised at the time of declaration.
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
Not asked since 2022
Definition. Unions are used where one memory area must hold different types at different times.
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
Not asked since 2022
Definition. User-defined data types are types made by the programmer, using struct, union, enum and typedef.
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.