speed007
speed007

Reputation: 19

Passing a constant reference into a function

I am trying to pass a constant integer into a function using pass by reference.

#include <iostream>
using namespace std;

int test(int& num);
// changes a constant variable

int main() {
  int loopSize = 7;
  const int SIZE = loopSize;
  cout<<SIZE<<endl;
  test(loopSize);
  cout<<SIZE;
  return 0;
}

int test(int& num){
  num -= 2;
}

However, the output is never updated.

Upvotes: 1

Views: 106

Answers (2)

Thai Q. Nguyen
Thai Q. Nguyen

Reputation: 26

You are changing loopSize and printing SIZE, so obviously the value won't change. Also, SIZE is a const, it won't change anyway.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

SIZE and loopSize are two different objects. Even though SIZE started its life with loopSize's value at the time, changing one won't change the other. SIZE is not a reference.

Indeed, since SIZE is a constant you could never reasonably expect it to change anyway!

Is it possible that you intended to write the following?

const int& SIZE = loopSize;
//       ^

Upvotes: 6

Related Questions