0

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;
}
Cartier
  • 19
  • 5
  • 4
    This variable is being passed by value, not by reference. Read on: https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Hanlet Escaño Dec 03 '21 at 18:36
  • 1
    It's also [undefined behavior](https://en.cppreference.com/w/cpp/language/return) to reach the end of a value-returning function like `valuered` without actually returning anything. – Nathan Pierson Dec 03 '21 at 18:38
  • 1
    You need a reference `void valuered(int& value)` – infinitezero Dec 03 '21 at 18:38

2 Answers2

7

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.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Salvage
  • 448
  • 1
  • 4
  • 13
0

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;
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 04 '21 at 06:25