C Pass-By-Reference


All Parameter Passing in C is Pass-by-Value

 

Pass-by-value means a copy of the value is made and passed to the function

 

    #include <stdio.h>

    /* Code illustrating pass-by-value */

    void addOne(int x);

    void main()
    {
        int y = 3; /* 1 */
        addOne(y);
                   /* 4 */

        printf ("%d\n", y);
    }

    void addOne(int x) /* takes an int parameter */
    {
                   /* 2 */
        x++;       /* 3 */
    }


Using Pointers to Achieve the Effect of Pass-by-Reference

 

Pass-by-reference means a reference to the value is passed to the function

 

    #include <stdio.h>

    /* Code illustrating pass-by-reference */

    void addOne(int * x);

    void main()
    {
        int y = 3; /* 1 */
        addOne(&y);
                   /* 4 */

        printf ("%d\n", y);
    }

    void addOne(int * x) /* takes a pointer to an int */
    {
                   /* 2 */
        (*x)++;    /* 3 */
    }

diagram of main passing address of y to addOne

Alyce Brady, Kalamazoo College