Skip to content
Justice Tech School

Pass by Value, Reference and const Reference

Pass by value copies. Pass by reference avoids copies. const reference is safe and fast for big objects.

Example
#include <iostream>
#include <string>

size_t len(const std::string &s) { return s.size(); }
void shout(std::string &s) { for (auto &c : s) c = toupper(c); }

int main() {
  std::string s = "hello";
  std::cout << len(s) << " ";
  shout(s);
  std::cout << s << "\n";
  return 0;
}

Result

5 HELLO

Exercise

Read only no copy.

void f( std::string &s)

Quiz Test

Best for large read only input?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.