Functions in C++: The Main Function & Function Prototyping
Overview: A prototype tells the compiler which arguments a function accepts before the function’s body appears.
What is a Function?
- A Function is a reusable block of code written to perform a specific task.
- A function works the same way: you pass inputs (arguments), it does the work, and gives you back the answer.
- Why Do We Use Functions?: No Duplicate Code: Write the logic once and call it as many times as you like.
- Easy to Understand (Modularity): Instead of writing 500 lines in
main(), break your project into small, neat functions (likeadd(),calculateBill(),… - Easy to Find Bugs: If the bill total is wrong, you only need to check the
calculateBill()function.
The main() Function in C++
- Every single C++ program must have a
main()function. - Important Questions Asked by DAVV Examiners: Why
int main()instead ofvoid main()? - What does
return 0;mean? - What if I forget to write
return 0;?
Function Prototyping (Why is it Required?)
- In old C language, you could call a function without telling the compiler in advance.
- The name of the function.
- What data type it returns.
- How many arguments (parameters) it expects, and their data types.
- Return Type What kind of data the function sends back ( int , float , void ).
- Function Name The name you use to call it (e.g., findMax ).
- Parameter List Types of inputs it expects (e.g.
- Semicolon (;) A prototype always ends with a semicolon ; because it is just a declaration.
View diagram · Anatomy of a Function Prototype
Code Example: Prototype, Call & Definition
- Here is how all 3 pieces work together in a complete program:
- How Does the Compiler Check It?: When the compiler sees
findMax(num1, num2)insidemain(), it checks the prototype above: - Does
findMaxaccept 2 arguments? - Are they both integers?
- Does the return value match
int result?
Call by Value, Address & Reference in C++: Swapping & Return by Reference
Overview: Pass a mark by value and the function updates a copy.
Actual vs. Formal Parameters
- When you work with functions in C++, there are two types of parameters:
- Actual Parameters (Arguments): The real values or variables you pass when calling the function from
main()(for example, inswap(a, b);,aandb… - Formal Parameters: The parameter variables written in the function definition header that receive those values (for example, in `void swap(int…
The Three Ways to Pass Parameters in C++
- A value parameter gets a copy while a reference parameter aliases the caller’s object.
- 1. Call by Value A duplicate copy of the value is passed.
- 2. Call by Address (Pointers) The memory address ( &a ) is passed to a pointer ( int *x ).
- 3. Call by Reference (C++ Alias) A reference nickname ( int &x ) is passed.
View diagram · Parameter Passing Mechanisms in C++
The Classic Swapping Problem: Comparing All Three
- Let us understand the three methods by trying to swap two numbers (
a = 10andb = 20): - A. Call by Value (Does NOT Swap Original Values): Why it fails:
xandyare just temporary copies. - B. Call by Address (Swaps Using C Pointers): Here, instead of values, we pass the memory addresses (
&a,&b) to pointers (*x,*y). - C. Call by Reference (The Best C++ Way): In C++, you can pass parameters as references (
&x).
Comprehensive Comparison Table
- This table is frequently asked in DAVV BCA exams:
- What is passed?: A copy of the value
- Original Value Changes?: No (stays unchanged)
- Call Syntax:
swap(a, b); - Function Header:
void swap(int x, int y) - Extra Memory Used?: Creates new copy variables
- Can it be NULL?: No
Return by Reference in C++
- In regular C, a function can only return a value.
- Important Rule for Exams:
- Never return a reference to a local variable! Local variables get destroyed as soon as the function finishes.
Inline Functions in C++: Working, Overhead & Restrictions
Overview: An inline function uses ordinary parameter types and scope.
The Problem: Normal Function Call Overhead
- Normally, when a C++ program calls a function, your CPU does a lot of background work:
- Save Context CPU saves active registers & return address to stack
- Push Arguments Passes parameters across memory boundaries
- Jump & Execute Jumps to function body in code segment
- Return & Resume Returns value and jumps all the way back to main()
View diagram · Execution Overhead of a Standard Function Call
The Solution: Inline Functions
- To make small functions super fast, C++ gives us the
inlinekeyword. - Normal Function (JUMP) int res = cube(5); CPU pauses, pushes data onto the stack, jumps to cube() address, runs it, and jumps back.
- Inline Function (COPY-PASTE) int res = cube(5); Compiler replaces it directly at compile time with: int res = 5 * 5 * 5; (Zero jumping overhead!
View diagram · Normal Function Call vs. Inline Function Expansion
Inline Functions vs. Preprocessor Macros (#define)
- In C language, programmers used
#definemacros (like#define CUBE(x) (x*x*x)) to avoid jumping overhead. - Who handles it?: Handled by the C++ Compiler
- Type Checking: Strict type checking by the compiler (safe)
- Safe with Operators?: Fully safe:
cube(x++)works properly - Classes & OOP: Can be a member of a class and access private data
- Debugging: Easy to trace with a debugger
When Does the Compiler Reject Inlining?
- Important Rule for Exams:
- Writing
inlineis just a request or suggestion to the compiler, not an order. - Contains Loops: If the function contains
for,while, ordo-whileloops. - Recursive Functions: If the function calls itself (recursion cannot be expanded infinitely).
- Contains
switchorgoto: If the function has complicated jumps. - Contains
staticvariables: If it contains static local variables. - Too Long / Too Big: If the function has 20–30+ lines of code.
Default Arguments & Constant Arguments in C++
Overview: A function can use a default tax rate when the caller omits that argument.
What are Default Arguments?
- In C language, if a function takes 3 inputs, you must pass all 3 inputs every single time you call it.
The Strict “Right-to-Left” Rule (Golden Exam Rule)
- When adding default values to parameters, you must start from the rightmost parameter and move left.
- VALID Declarations • void func(int a, int b, int c = 50); (Rightmost only) • void func(int a, int b = 20, int c = 50); (Right two) • void…
- INVALID Declarations (Compiler Error) • void func(int a = 10, int b, int c = 50); (Middle missing!) • void func(int a = 10, int b, int c); (Rightmost missing!)…
View diagram · Default Arguments Rule Validation
Practical Code Example: Simple Interest Calculator
- Crucial Rule: Define default values in the Function Prototype (declaration) only.
Constant Arguments (const Parameters)
- Sometimes you want to make sure that a function cannot change an argument by mistake.
- Why Use
const &(Constant Reference) in C++?: When passing large objects (like aStudentrecord with 50 fields): - Pass by Value (
Student s): Safe, but creates a duplicate copy in RAM, wasting time and memory. - Pass by Reference (
Student &s): Super fast (no copying), but the function can accidentally change your original data! - Pass by Constant Reference (
const Student &s): The best of both worlds! - Zero copying (super fast because it passes a reference).
- 100% safe (because
constprevents any modification).
Function Overloading & Passing Arrays to Functions in C++
Overview: A compiler can distinguish print(int) from print(double) by their parameter types.
What is Function Overloading?
- In C language, if you want to calculate the area of a square, circle, and rectangle, you have to create three separate names:
areaSquare(),… - In C++, having one name with multiple behaviors is called Polymorphism (Compile-Time Polymorphism).
Rules for Function Overloading (Exam Golden Rules)
- Two functions with the same name can be overloaded if they differ in at least one of these 3 ways:
- 1. Number of Arguments int add(int a, int b); int add(int a, int b, int c); (Takes 2 vs 3 parameters)
- 2. Data Types of Arguments float add(float a, float b); int add(int a, int b); (Takes floats vs integers)
- 3. Order / Sequence of Types void show(int a, float b); void show(float a, int b); (Different sequence)
- ⚠️ MOST ASKED EXAM QUESTION:
- Can we overload a function based on Return Type alone?
- NO, NEVER!
- If you write:
View diagram · Valid Overloading Criteria
Passing Arrays to Functions in C++
- When you pass an ordinary variable like
int xto a function, C++ makes a separate copy of it (Call by Value). - Passing Two-Dimensional (2D) Arrays: When passing a 2D matrix to a function, the column size is mandatory in the brackets!