1

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.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
speed007
  • 19
  • 2
  • 1
    `test(SIZE)` not `test(loopSize)` – Luca Apr 19 '15 at 02:43
  • 2
    But you shouldn't try to modify a constant anyway. – Luca Apr 19 '15 at 02:43
  • I am very new to C++, but what is going on with this line? `int test(int& num); // changes a constant variable` – tjons Apr 19 '15 at 02:44
  • It's not hard to get around `const` if you try, but it's your own fault when things break. – chris Apr 19 '15 at 02:45
  • You can't change the value of constant this way – user2736738 Apr 19 '15 at 02:45
  • 1
    @tjons, It declares a function `test` that takes a reference to `int` and returns `int`. – chris Apr 19 '15 at 02:45
  • @chris thanks for answering. But if that is so, why is the function body later defined? Why not do it all at once? – tjons Apr 19 '15 at 02:46
  • @tjons, Various reasons, but this isn't the place. I recommend picking up a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – chris Apr 19 '15 at 02:48
  • 3
    Your question is equivalent to this: `a = 2; b = 4;` `b -= 2;` Can anyone tell me why `a`'s value doesn't change? – Adam Apr 19 '15 at 02:49
  • 1
    @tjons: In this particular example, there is no reason. `test` could have been defined first. I would have done. In such examples it tends to be because people are taught this way, mostly from C heritage. In practice, function definitions tend to be hived off into other files so that could be why. But you're right to question it in this particular example. – Lightness Races in Orbit Apr 19 '15 at 02:58

2 Answers2

6

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;
//       ^
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

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