Junior — Middle
Could you explain how passing variables by reference works in programming?
sobes.tech AI
Answer from AI
Passing variables by reference means that instead of passing a copy of the variable's value to a function or method, a reference to the variable itself is passed. This allows the function to modify the original data.
For example, in Kotlin (often used for Android), passing by reference is not directly supported, but you can use objects or special wrapper classes to simulate this behavior.
In C++ or C#, you can explicitly pass parameters by reference:
void Increment(ref int number) {
number += 1;
}
int x = 5;
Increment(ref x);
// Now x == 6
Passing by reference is useful when you need to change the value of a variable in the calling code or to avoid copying large data structures.