Parameter passing in C++

To run a C++ program:

The example illustrates parameter passing in (old style) C++


#include <iostream>  // need this header file to support the C++ I/O system
using namespace std; // using the standard namespace "std",

// function declarations - needed for the program to compile
void by_value(int n);
void by_reference(int *p);
void swap(int *p, int *q);

int main()
{
  int n = 2, m = 1;
  int *p = &n;
  int *q = &m;

  // passing an integer by value
  by_value(n);
  cout << n << endl;
  by_value(*p); // cannot pass just p
  cout << n << endl;

  by_reference(&n); // cannot pass just n
  cout << n << endl;
  by_reference(p);
  cout << n << endl;

  // swaping n and m
  swap(&n, &m);
  cout << "n = " << n << " m = " << m << endl;

  swap(p, q);
  cout << "n = " << n << " m = " << m << endl;

  return 0;
}

void by_value(int k) {
  k = k + 1;
}

void by_reference(int *r) {
  *r = *r + 1;
}

void swap(int *first, int *second) {
  int temp = *first;
  *first = *second;
  *second = temp;
}


CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.