Reputation: 23
Why is this code not adding one to the int numbers?
Forgive me for posting a very easy question, I am new to c++.
The value of numbers seem to be unaffected when appearing in the console. Am I incorrectly passing the function's argument?
#include <iostream>
int number = 0;
int addOne(int a);
int main()
{
std::cout << "Please type a number to add to one: ";
std::cin >> number;
std::cout << number << " plus one equals: ";
int addOne(number);
std::cout << number;
}
int addOne(int a) {
return a++;
}
Upvotes: 1
Views: 217
Reputation: 33526
One more possibility, your function already returns value.
Why not use it?
int addOne(int a) { // no &, still passed as copy
a++; // increase the copy
return a; // return value AFTER increase has been done on 'a'
}
number = 2;
number = addOne(number); // copy in (2), copy out (3)
std::cout << number; // now it's 3
Upvotes: 1
Reputation: 496
You're passing the variable by value, which means that the value inside the function will be a copy and the original value will not be modified.
Upvotes: 1
Reputation: 75062
Function arguments are copied by default, so modifying the copy (in this case a
) won't affect the original (in this case number
).
To have functions modify caller's variables, you should use reference.
Also note that int addOne(number);
in your main
function is not a function call but a declaration of a variable addOne
with initializing it to number
.
#include <iostream>
int number = 0;
int addOne(int& a); // add "&"
int main()
{
std::cout << "Please type a number to add to one: ";
std::cin >> number;
std::cout << number << " plus one equals: ";
addOne(number); // remove "int"
std::cout << number;
}
int addOne(int& a) { // add "&"
return a++;
}
Upvotes: 2