1. Gyanastra
  2. Programming Languages
  3. Programming in C++
  4. C++ Basics References and Functions
Free lesson, no account needed 11 min read 22 practice questions after it
Asked in past papers6 times
  • GATE CSE2013
  • ISRO20182014
  • UGC NET201820162013

Programming Languages · Programming in C++

C++ Basics References and Functions

Overview

C++ provides several ways to pass arguments to functions and to make functions efficient and expressive.
This lesson covers reference variables, the three parameter-passing mechanisms (by value, by pointer, by reference), default arguments, inline functions, function overloading, return by reference, and the scope resolution operator.
These features are heavily tested in UGC NET through code-tracing and statement-based questions because they depend on precise rules, not memorisation.
Before studying this lesson, you should know basic C++ syntax, data types, variables, pointers, and how a function is declared and defined.

Key concepts

  • Reference variable: An alias for an existing object. Declared as int &r = x;. Must be initialised at declaration; cannot be made to refer to another object later; no null reference.
  • Pass by value: The formal parameter is a copy of the actual argument. Changes inside the function do not affect the caller's variable.
  • Pass by pointer: The formal parameter is a pointer holding the address of the actual argument. The function can modify the caller's variable using *p, provided the pointer is valid.
  • Pass by reference: The formal parameter is an alias of the actual argument. Changes inside the function directly modify the caller's variable.
  • const reference parameter: const T & binds to the argument without copying and forbids modification through the reference. Preferred for large objects.
  • Default argument: A value supplied in the function declaration that is used when the caller omits that argument.
    Defaults must be trailing (rightmost) parameters; once a parameter has a default, all parameters to its right must also have defaults.
  • Inline function: A function declared with the inline keyword. It suggests to the compiler that the function body be substituted at each call site to avoid call overhead. The compiler may ignore the suggestion.
    Typically defined in a header; multiple identical definitions across translation units are allowed under the One Definition Rule (ODR).
  • Function overloading: Multiple functions with the same name but different parameter lists (different number, types, or order of parameters). Return type alone cannot distinguish overloads.
    The compiler resolves the call at compile time (static polymorphism).
  • Function signature: In C++, the signature for overloading is the function name plus the parameter types (and for member functions, const/ref qualifiers). Return type is not part of the signature.
  • Return by reference: A function returns an alias (lvalue) to an object. Safe only if the referred object outlives the function call (e.g., static local, global, or a parameter passed by reference).
    Returning a reference to a local automatic variable is undefined behaviour.
  • Scope resolution operator ::: Used to qualify a name. ::x refers to the global x when a local x shadows it; Class::member defines or accesses a class member outside the class.
  • Array parameter decay: A parameter declared as int a[] or int a[10] is adjusted to int *a. Therefore sizeof(a) inside the function gives the pointer size, not the array size.

How it works

  1. Function declaration and definition: A declaration (prototype) tells the compiler the function's name, return type, and parameter types. A definition provides the body.
    Default arguments are normally specified in the declaration, not repeated in the definition.
  2. Parameter binding at call time:
    • By value: the argument expression is evaluated and its value is copied into the parameter. The parameter is a distinct object.
    • By pointer: the argument must be an address (or a pointer). The pointer parameter is a copy of that address; dereferencing it accesses the caller's object.
    • By reference: the parameter is bound directly to the argument object; no copy is made. The argument must be an lvalue (something with an address) unless the reference is const.
  3. Modification semantics:
    • Value parameter: modifying the parameter changes only the local copy.
    • Pointer parameter: *p = value modifies the caller's object; p = other changes only the local pointer.
    • Reference parameter: any assignment to the parameter modifies the caller's object.
  4. Default arguments: At the call site, omitted trailing arguments are filled with defaults. You cannot omit an earlier argument while supplying a later one. Default expressions are evaluated at the call site.
    A default argument cannot be redefined in the same scope.
  5. Inline expansion: The compiler may replace a call with the function body. This eliminates call/return overhead but can increase code size.
    Recursive functions, functions with loops, or functions whose address is taken are often not inlined. inline is a request, not a command.
  6. Overload resolution: The compiler collects functions with the same name, forms candidate sets, and chooses the best match based on exact match, promotions, and conversions. Ambiguity arises when two overloads are equally good.
    Overloading is resolved at compile time; virtual functions (runtime polymorphism) are a different topic.
  7. Return by reference: The function's return type is T&. The returned expression must be an lvalue that remains valid after the function returns. It can be used on the left side of an assignment, enabling expressions like pick(a,b) = 100;.
  8. Scope resolution: Inside a function, a local variable can hide a global variable. Use ::name to access the global. For class members, ClassName::member accesses the class scope.
Figure. Notice that by value the formal parameter copies x, so changes do not affect x; by pointer or reference, changes through the parameter affect x.

Worked examples

Example 1 (pass by value and reference)

#include <iostream>
using namespace std;
void change(int a, int &b) {
    a = a + 10;
    b = b + 10;
}
int main() {
    int x = 5, y = 7;
    change(x, y);
    cout << x << " " << y;
    return 0;
}

Trace: x is passed by value to a, so a becomes 15 but x remains 5. y is passed by reference to b, so b = 7 + 10 = 17 changes y to 17. Output: 5 17.

Example 2 (default arguments and overloading)

#include <iostream>
using namespace std;
int area(int s, int t = 2) { return s * t; }
int main() {
    cout << area(3) << " " << area(3, 4);
    return 0;
}

area(3) uses default t = 2, returns 3×2 = 6. area(3,4) returns 3×4 = 12. Output: 6 12. Note: if a function is declared as int f(int a, int b = 4, int c = 5);, valid calls are f(1), f(1,2), and f(1,2,3). You cannot call f(1, , 3).

Example 3 (reference aliasing)

#include <iostream>
using namespace std;
int main() {
    int x = 10;
    int &r = x;
    r = 20;
    int y = r;
    y = 30;
    cout << x << " " << r << " " << y;
    return 0;
}

r is an alias of x. r = 20 makes x = 20. y = r copies 20 into y. y = 30 changes only y. Output: 20 20 30.

Example 4 (pointer parameter and common trap)
The correct pointer-based swap is:

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Call with swap(&p, &q);. A common mistake is declaring int *temp; and writing temp = a; a = b; b = temp;—this swaps the pointer values, not the pointed-to integers, and does not modify the caller's variables. The temporary must be int and the values must be accessed through *a and *b.

Example 5 (return by reference and dangling reference)

#include <iostream>
using namespace std;
int& bad() {
    int local = 5;
    return local;   // undefined behaviour
}
int& good(int &x) {
    return x;
}
int main() {
    int a = 3;
    good(a) = 9;
    cout << a;
    return 0;
}

good(a) returns a reference to a, so good(a) = 9 assigns 9 to a. Output: 9. The function bad() returns a reference to a local variable whose lifetime ends when bad() returns; using that reference is undefined behaviour. This is a standard UGC NET assertion-reason trap.

Comparison

FeaturePass by valuePass by pointerPass by reference
Formal parameterCopy of argumentPointer holding addressAlias of argument
Can modify caller?NoYes, via *pYes
Null allowed?Not applicableYesNo (must bind to object)
Rebindable?Not applicableYes (pointer can point elsewhere)No
Syntax at callf(x)f(&x)f(x)
Common useSmall data, no side effectsC-style arrays, optional argumentsLarge objects, output parameters
ConceptKey ruleTrap
Default argumentsMust be trailing; specified in declarationCannot skip middle arguments
Function overloadingDifferent parameter list; return type ignoredTwo functions differing only in return type are illegal
Inline functionSuggestion to compiler; not mandatoryCompiler may ignore; recursive functions often not inlined
Return by referenceMust return valid lvalueReturning local automatic variable is undefined
Reference variableMust be initialised; cannot be reboundint &r; is illegal

Revision summary

  • A reference is an alias; it must be initialised and cannot be reseated.
  • Pass by value copies; pass by reference aliases; pass by pointer copies an address.
  • In a pointer swap, the temporary must be int, not int *, and use *a and *b.
  • Default arguments are filled from right to left; you cannot skip a middle argument.
  • inline is a request; the compiler may ignore it.
  • Overloading depends on parameter types, number, and order—not return type.
  • Return by reference to a local variable is undefined; use static, global, or caller-owned objects.
  • ::x accesses the global x when a local x shadows it.
  • Array parameters decay to pointers; sizeof inside gives pointer size.
  • const T& avoids copying and forbids modification.
  • The scope resolution operator also defines class member functions outside the class.
  • Function overloading is compile-time polymorphism; virtual functions are runtime polymorphism.

Previous-year exam insights

  • UGC NET often gives three swap implementations (value, reference, pointer) and asks which actually exchange caller values.
    Check the parameter declaration and the use of * in the body.
  • Code-tracing questions test aliasing: int &r = x; r = y; changes x, not the reference binding.
  • Default-argument questions ask how many arguments can be supplied or whether a declaration is well-formed.
    Remember the trailing rule.
  • Statement I/II questions test inline functions: inline is a suggestion, ODR permits identical definitions in headers, and the compiler is not obliged to inline.
  • Match-the-list questions pair parameter forms (int, int&, const int&, int*) with their modification and copying behaviour.
  • Assertion-reason questions frequently use returning a reference to a local variable as the classic undefined-behaviour assertion.
  • Overloading questions check whether return type alone can distinguish overloads (it cannot) and whether default arguments can create ambiguity.
  • Scope-resolution questions test global versus local shadowing and class-member definitions.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Explain the difference between a reference variable and a pointer, including initialisation, rebinding, and nullability.
  • Trace a program that passes arguments by value, by pointer, and by reference, and state the exact output.
  • Write a correct pointer-based swap and identify the bug in a wrong version that uses int *temp.
  • Determine the output of code using default arguments and list all valid call signatures for a given prototype.
  • State whether a given use of inline guarantees inlining and why.
  • Identify whether two function declarations form a valid overload or an illegal redefinition.
  • Explain why returning a reference to a local automatic variable is dangerous and when returning a reference is safe.
  • Use the scope resolution operator to access a shadowed global variable and to define a class member outside the class.
  • Distinguish const T& from T& and T* in terms of copying and modification.
  • Analyse a match-the-list or assertion-reason question on parameter passing and return types.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2