Cartier
Cartier

Reputation: 19

Why isn't the 'number' value changing?

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;
}

Upvotes: 0

Views: 108

Answers (2)

Code_it_Abdullah
Code_it_Abdullah

Reputation: 1

pass by reference is important to use the modified value out side the function because if you are using pass by value then the change in value will only exist inside the user defined function.

    #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;
}

Upvotes: 0

Salvage
Salvage

Reputation: 509

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.

Upvotes: 7

Related Questions