🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #78

Pass By Reference


Pass By Reference

In the examples from the previous page, we used normal variables when we passed parameters to a function.

You can also pass a reference to the function.

This can be useful when you need to change the value of the argument(s):

Example

void changeValue(int &num) {
  num = 50;
}

int main() {

int value = 10;
  changeValue(value);  // Call the function and
change the value to 50
  cout << value;
  return 0;
}

Example

void swapNums(int &x, int &y) {
  int z = x;
  x = y;

y = z;
}

int main() {

int firstNum = 10;
  int secondNum = 20;

  cout <<
"Before swap: " << "\n";
  cout << firstNum << secondNum << "\n";

  // Call the function, which will change the values of firstNum
and secondNum
  swapNums(firstNum, secondNum);

  cout << "After swap:
" << "\n";
  cout << firstNum << secondNum << "\n";

return 0;
}

Example

void modifyStr(string &str) {
  str += " World!";
}

int main() {

string greeting = "Hello";
  modifyStr(greeting);
  cout <<
greeting;
  return 0;
}

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Pass By Reference – FAQs

Quick answers about learning Pass By Reference in C++.

This free note from CodingNow 2.0 explains Pass By Reference in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including Pass By Reference, is 100% free with no signup required.
With focused practice, most students grasp Pass By Reference in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now