Search code examples
c++c

How does call by value and call by reference work in C?


In a C program, how does function call by value work, and how does call by reference work, and how do you return a value?


Solution

  • Call by value

    void foo(int c){
        c=5; //5 is assigned to a copy of c
    }
    

    Call it like this:

    int c=4;
    foo(c);
    //c is still 4 here.
    

    Call by reference: pass a pointer. References exist in c++

    void foo(int* c){
        *c=5; //5 is assigned to  c
    }
    

    Call it like this:

    int c=0;
    foo(&c);
    //c is 5 here.
    

    Return value

    int foo(){
        int c=4;
         return c;//A copy of C is returned
    }
    

    Return through arguments

       int foo(int* errcode){
    
           *errcode = OK;
    
            return some_calculation
       }