0

How can I change number in get_number using the function increaseNumber if increaseNumber has to be void?

#include<iostream>
using namespace std;

void increaseNumber(int64_t number){
    number++;
}

int64_t get_number(){
    int64_t number = 0;
    increaseNumber(number);
    return number;
}

int main(void){

    cout << get_number();
}

If it is of any help, I have tried changing an array rather than an integer and that worked fine.

digito_evo
  • 3,216
  • 2
  • 14
  • 42

1 Answers1

1

The problem is that you declared the function increaseNumber in such a way that the parameter is passed by value:

void increaseNumber( int64_t number )

That way, it is passed a copy of the value of the variable number of the function get_number. Therefore, modifying the variable number of the function increaseNumber will not change the variable number of the function get_number, as these are two separate variables.

If you instead want the original variable's value to be modified too, then you should not pass a copy of the variable's value, but you should instead declare the function in such a way that a reference to the original variable is passed:

void increaseNumber( int64_t& number )

That way, no copy of the original variable will be made, and your program should work as intended, without any further modifications being necessary.

The reason why using an array worked with you is that if you pass an array, it will decay to a pointer, which is equivalent to a reference.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • How about `int64_t* const number` and then `++(*number)`? – digito_evo Jan 22 '22 at 12:27
  • @digito_evo: Yes, passing the variable by pointer would be the C-style way of solving the problem, but passing the variable by reference is the common way to solve the problem in C++. In C++, there is [call by value](https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_value.htm), [call by pointer](https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_pointer.htm) and [call by reference](https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm). In C, there is only the first two. – Andreas Wenzel Jan 22 '22 at 12:32