// this C program illustrates passing by value and by address (by reference) to accomplish the same thing.

 

Executable

 

#include <stdio.h>

int doubleit(int);

void otherway(int *);

 

int main()

{

        int anum, bnum;

 

        anum = 5;

        printf("\n main() anum = %d ",anum);

        printf("\n main() bnum = %d ",bnum);

        getchar();    /*getchar() pauses the program until the user presses a key on the keyboard */

  

bnum = doubleit(anum); /* anum is passed by value to doubleit.

Doubleit mulitiplies it by 2 and returns it.

The returned value is placed in bnum */

        getchar();

 

printf("\n\n main() anum = %d ",anum);

        printf("\n main () bnum = %d ",bnum);

        getchar();

 

        otherway(&anum); /* anum is passed by address to otherway Doubleit mulitiplies it by 2 

and places the result at the address passed to it the address of main()’s anum*/

        getchar();

 

        printf("\n\n main() anum = %d ",anum);

        getchar();

       

        return 0;

}

 

int doubleit(int doubled)   /* doubleit declares an integer to receive the value passed to it */

{

printf("\ndoubleit() before value doubled = %d ", doubled);

 

doubled *= 2;

        printf("\ndoubleit() after value doubled = %d ", doubled);

 

        return doubled;    /* doubleit returns the value after doubling */

}

void otherway(int * anum_ptr) /* doubleit declares a pointer to an integer to receive the value passed to it */

{

        printf("\n\n\notherway() anum  = %d ", * anum_ptr);

        printf("\notherway() anum_ptr = %p ", anum_ptr);

        printf("\notherway() address of anum_ptr = %p ", &anum_ptr);

       

*anum_ptr *= 2;

 

        printf("\n\n\notherway() anum = %d ", * anum_ptr);

        printf("\notherway()anum_ptr = %p ",  anum_ptr);

        printf("\notherway() address of anum_ptr = %p ", &anum_ptr);

       

return;

}