in this code snipped you declared a function with an argument passed to it by value:
void increment(int value) {
value++;
}
What it really does, it increments this value … inside the function, and that is it. It does not return the value nor updates any other variable.
There are several ways you can address the problem.
- you can return the value from the function in a classical manner:
int increment(int value) {
value++;
return value;
}
int main() {
int a = 5;
a = increment(a);
...
}
In the above example new value of a
will be incremented.
- you can use pointers to update a variable which was declared outside the scope of the function. You can think of pointers as addresses of the variable.
void increment(int *pointer) {
(*pointer)++;
}
int main() {
int a = 5;
a = increment(&a);
...
}
In the above example you updated value of the variable a
by using its address (pointer).
- you can use references. They are just proxys to a variable and in general behave as pointers. The difference is that allow a syntax appropriate for a proxy:
void increment(int &proxy) {
proxy++;
}
int main() {
int a = 5;
a = increment(a);
...
}
In this case proxy is just a way to reference the variable outside the function scope and ++ will update the value of variable a
solved Confused as to why increment function doesn’t actually increment variable [closed]