https://rentry.org/PPP2_p275

// Code derived from Stroustrup's PPP2 book
// § 8.5.3 Pass-by-value
//  -and beginning on p 275

#include <iostream>

using namespace std;

int f(int x)  // pass-by-value (give the function a copy of the value passed)
{
  x = x + 1;  // give the local x a new value
  return x;
}

int main()
{
  int xx = 0;
  cout << f(xx) << endl;  // print: 1
  cout << xx << endl;     // print: 0; f() doesn't change xx

  int yy = 7;
  cout << f(yy) << endl;  // print: 8
  cout << yy << endl;     // print: 7; f() doesn't change yy
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p275.cpp && ./a.out

PrevUpNext

Edit
Pub: 04 Apr 2023 14:41 UTC
Edit: 02 May 2023 23:35 UTC
Views: 553