C++ Tutorial menu

C++ Functions

A function is a named block of code that does one job. You can call it as many times as you like.

Creating and Calling a Function

Example

cpp
#include <iostream>
using namespace std;

void showLine() {
  cout << "--------------------\n";
}

int main() {
  showLine();
  cout << "  Workownix Receipt\n";
  showLine();
  return 0;
}
Output
--------------------
  Workownix Receipt
--------------------

A function must be declared before it is called. Either write it above main, or put a declaration like void showLine(); at the top.

Parameters and Return Values

Example

cpp
#include <iostream>
using namespace std;

double average(int a, int b, int c) {
  return (a + b + c) / 3.0;
}

bool isEven(int n) {
  return n % 2 == 0;
}

int main() {
  cout << average(70, 85, 90) << "\n";
  cout << boolalpha << isEven(14) << "\n";
  return 0;
}
Output
81.6667
true

Default Arguments

A parameter can have a default value that is used when you leave it out:

Example

cpp
#include <iostream>
#include <string>
using namespace std;

void greet(string name, string city = "Karachi") {
  cout << name << " from " << city << "\n";
}

int main() {
  greet("Ayesha");
  greet("Usman", "Multan");
  return 0;
}
Output
Ayesha from Karachi
Usman from Multan

Function Overloading

Several functions can share a name if their parameter lists are different:

Example

cpp
int area(int side) { return side * side; }
int area(int length, int width) { return length * width; }

// area(5) gives 25, area(4, 6) gives 24

Pass by Value and Pass by Reference

By default, C++ passes a copy of the argument. Add & to the parameter type to pass a reference, so the function works on the original variable:

Example

cpp
#include <iostream>
using namespace std;

void addCopy(int x) {
  x += 10;
}

void addRef(int& x) {
  x += 10;
}

int main() {
  int points = 5;
  addCopy(points);
  cout << points << "\n";
  addRef(points);
  cout << points << "\n";
  return 0;
}
Output
5
15
StyleParameterChanges the original?
By valueint xNo
By referenceint& xYes
By const referenceconst string& sNo, and it avoids copying

For big objects like strings and vectors that the function only reads, use const references (const vector<int>& v). It is faster because nothing is copied.

Recursion

Example

cpp
int power(int base, int exp) {
  if (exp == 0) return 1;
  return base * power(base, exp - 1);
}
// power(2, 10) gives 1024

Exercise

Exercise

Which parameter lets a function change the caller's variable directly?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp