Function Parameters

Pass by value, reference, and pointer

Interview Relevant: Critical for interviews

Function Parameters

C++ offers multiple ways to pass arguments to functions.

Passing Methods

  • By value: Copy of the argument (safe, but copies)
  • By reference: Direct access to original (efficient, can modify)
  • By const reference: Efficient read-only access
  • By pointer: Address of the argument

Code Examples

Different parameter passing methods in C++.

cpp
1// Pass by value (copy)
2void incrementValue(int x) {
3    x++;  // Only modifies local copy
4}
5
6// Pass by reference (modifies original)
7void incrementRef(int& x) {
8    x++;  // Modifies the original
9}
10
11// Pass by const reference (efficient, read-only)
12void print(const vector<int>& vec) {
13    for (int n : vec) cout << n << " ";
14}
15
16// Pass by pointer
17void incrementPtr(int* x) {
18    (*x)++;
19}
20
21int val = 5;
22incrementValue(val);   // val still 5
23incrementRef(val);     // val is now 6
24incrementPtr(&val);    // val is now 7

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In