Sobes.tech
Junior — Middle

How can a function change the parameter it receives?

sobes.tech AI

Answer from AI

In C/C++, a function can modify the parameter passed to it in several ways:

  1. Passing by pointer — the function receives the address of the variable, and by dereferencing the pointer, it changes the value at that address.
void increment(int* p) {
    (*p)++;
}

int main() {
    int a = 5;
    increment(&a); // a becomes 6
}
  1. Passing by reference (C++ only) — the function receives a reference to the variable, and changes inside the function affect the original.
void increment(int& ref) {
    ref++;
}

int main() {
    int a = 5;
    increment(a); // a becomes 6
}
  1. Passing by value with returning a new value — the function does not change the parameter directly but returns a new value that can be assigned to a variable.
int increment(int val) {
    return val + 1;
}

int main() {
    int a = 5;
    a = increment(a); // a becomes 6
}

Thus, for a function to modify a parameter, it must be passed either by pointer or by reference.