C Parameter passing

Review of by-value/by-reference 

 

By-Value:        The value of a variable is sent to function.

The actual parameter cannot be changed by function.

"In" parameter

 

By-Reference   An address gets sent to function.

                        The function can change the values at that address

                        "Out" or "In-Out"

 

Sending by reference in C requires the use of the pointer symbol (*).

 

            void f (int x)  // x is an integer

            {

                        x=x+1;

            }

            void h(int* p_x) // p_x is an address where an integer is stored.

            {

                        *p_x = *p_x + 1;

            }

 

Can call a by-reference function using the address operator &

 

            int x=9;

            f(x) ;   // f cannot change value of x.

            h(&x);  // h can change the value of x

 

Array parameters are similar to Java in effect

 

                        int array[10];                                        void g(int arr[])

                        //  put some stuff in it

                        // ...

                        g (array);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Trace the following:

 

            void f(int z)

            {

                        z=z+1;

            }

            void g(int a[])

            {

                        a[2]=8;

            }

void h(int *z)

{

                        *z = *z+1;

            }

            void main()

            {          int x=6;

                        int arr[5]

                        for (int i=0;i<5;i++)

                                    arr[i]=i;

                        f(x);

                        g(arr);

                        h(&x);

                        h(&(arr[4]));

            }