Functions

taimoor_ttaimoor_t karachi, pakistan

I am studying functions in c and i am confuse between pass by value and pass by reference?

Comments

  • Pass by value is copy of the variable where any changes made to it apply only within the scope of that function.

    Pass by reference is the address of the variable, which can be modified within a function and apply throughout the life of the variable

    void passByValue(int n) // copy of a variable
    { 
        n = 10;  // change is local to this function only
    }            
    
    void passByReference(int *n)  // address of a variable
    {
        *n = 10; // changes variable through its address
                 // n is a pointer to an address
                 // *n derefences the pointer to change the
                 // value at that address 
    }
    
    int main(void)
    {
        int x = 0;
    
        passByValue(x); // pass a copy of x to the function
        printf("passByValue: %d\n", x);       // x should still be 0
    
        passByReference(&x); // pass the address of x to the function
        printf("passByReference: %d\n", x);   // x should now be 10
    
        ...
    }

    HTH

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion