Functions and Structures
Functions and Structures
This domain tests modular programming with functions and grouping data with structures. A function has a return type, name, parameter list and body; a prototype tells the compiler the signature before use. Call by value copies arguments; call by reference passes aliases and can modify the caller's variables. Recursion is a function calling itself with a smaller problem and a base case.
Structures
A struct groups members of different types under one name. End the definition with a semicolon. Access members with the dot operator; an array of structures stores records; a structure can be passed to and returned from a function. Pointers to structures use the arrow operator.
Worked example
void swap(int &x, int &y) { int t = x; x = y; y = t; } called as swap(a,b) exchanges the originals. If declared void swap(int x, int y), only copies change, so the caller's a and b stay the same. This shows why reference parameters matter when a function must return two changed values.
For a structure: struct Student { int roll; float marks; }; then Student s = {12, 78.5}; and cout << s.marks; prints 78.5.
Traps
A missing semicolon after struct breaks compilation. Call by value cannot change the original. A function with return type void must not return a value. Recursion without a base case overflows the stack. Structure members are not automatically initialized in a local object.