Home > database >  Why isn't the 'number' value changing?
Why isn't the 'number' value changing?

Time:12-04

I'm trying to make a function that reduces a certain integer value by 30.

#include <iostream>

using namespace std;

int valuered(int value)
{
    value-=30;
}

int main()
{
    int number{100};
    valuered(number);
    cout<<number;

    return 0;
}

CodePudding user response:

You are passing value by value, meaning the valuered function has a local copy of the argument. If you want to affect the outside variable number the function should look like this:

void valuered(int& value)
{
    value-=30;
}

Here value is being passed by reference, meaning any changes done to it inside the function will propagate to the actual argument that has been passed in.

Also note that I have changed the return type from int to void, since you are not returning anything. Not returning anything from a function declared to return a value makes the program have undefined behavior.

CodePudding user response:

pass by reference is important to change the value.

    #include<iostream>
using namespace std;
int valuered(int &v) // pass  by reference is needed to use the modified value in main function.
{
    v-=30;
    return v;
}
int main()
{
    int number=100;
    valuered(number);
    cout<<number;
}
  • Related