Sobes.tech
Junior

Describe the methods of parameter passing in functions in C/C++.

sobes.tech AI

Answer from AI

There are three main ways to pass parameters to functions in C/C++:

  1. Pass by Value

    • A copy of the argument's value is passed to the function.
    • Changes to the parameter inside the function do not affect the original argument outside it.
    • Safe, but may be inefficient for large objects due to copying.
    void func_by_value(int x) {
        x = x * 2; // Only the local copy is changed
    }
    
    int main() {
        int a = 5;
        func_by_value(a);
        // a still equals 5
        return 0;
    }
    
  2. Pass by Reference

    • A reference (alias) to the original variable is passed.
    • Changes to the parameter inside the function directly affect the original argument.
    • Efficient, as no copy is made.
    • Const references (const &) can be used to prevent modifications.
    void func_by_reference(int& x) {
        x = x * 2; // Changes the original variable
    }
    
    int main() {
        int a = 5;
        func_by_reference(a);
        // a is now 10
        return 0;
    }
    
  3. Pass by Pointer

    • The address of the original variable is passed.
    • Modifications through dereferencing (*) affect the original argument.
    • Requires additional null pointer checks.
    • Allows passing a "null" value (nullptr) to indicate absence of an object.
    void func_by_pointer(int* x) {
        if (x != nullptr) {
            *x = *x * 2; // Changes the value at the address pointed to by x
        }
    }
    
    int main() {
        int a = 5;
        func_by_pointer(&a); // Passing the address of variable a
        // a is now 10
    
        func_by_pointer(nullptr); // Example of passing a null pointer
        return 0;
    }
    
Method What is passed Original change Efficiency (for large objects) Safety (modifications) Null value possibility Call syntax
By value Copy of the value No Low High No function(variable)
By reference Alias of the variable Yes High Low (if not const) No function(variable)
By pointer Address of the variable Yes (via *) High Medium (requires check) Yes (nullptr) function(&variable)