Sobes.tech
Junior — Middle

What are the features and differences in passing arguments to functions in C++?

sobes.tech AI

Answer from AI

In C++, function arguments can be passed in several ways, each with its own features:

  • By value: copies the argument's value. Changes inside the function do not affect the original.
  • By reference (&): the function receives a reference to the original object, and changes inside the function affect the argument.
  • By pointer (*): the address of the object is passed, allowing modification of the object but requiring a check for nullptr.

Features:

  • Passing by value is safe but can be costly for large objects.
  • Passing by reference is efficient and convenient, especially with const to prevent modifications.
  • Passing by pointer allows working with dynamic objects and indicating the absence of an object.

Example:

void foo(int val) { val = 10; }           // by value
void bar(int& ref) { ref = 10; }          // by reference
void baz(int* ptr) { if(ptr) *ptr = 10; } // by pointer

int main() {
    int a = 0;
    foo(a); // a remains 0
    bar(a); // a becomes 10
    baz(&a); // a becomes 10
}