Function Arguments (Again)


Parameter Passing

Example:
    #include <stdio.h>

    void call_by_value(int y) {
        y = 1;
      }

    void call_by_reference(int *y) {     /* param: pointer to int */
        *y = 1;                          /* de-ref pointer to int */
      } 

    main() {
        int x = 5;
        printf("original x = %d\n", x);

        call_by_value(x);
        printf("x should be the same as before, x = %d\n", x);

        call_by_reference(&x);
        printf("x should have changed, x = %d\n", x);
      }


Arrays as Arguments

We cannot pass the set of elements of an array as an argument, but we can pass the address of the array:


Example One:

    #include <stdio.h>
    #define SIZE 5

    int sum(int *data, int num_items) {
        int total, i;
 
        for (i = total = 0;  i < num_items; i++)   /* use expression-value */
            total = total + data[i];

        return total;
      }

    main() {
        int values[SIZE], i;

        for (i = 0;  i < SIZE; i++)      /* initialise array*/
            values[i] = i;

        printf("total = %d\n", sum(values, SIZE));
      }


Example Two (pointer arithmetic):

    #include <stdio.h>
    #define SIZE 5

    int sum(int *data, int num_items) {
        int total, i;
 
        for (i = total = 0;  i < num_items; i++) 
            total = total + *(data + i);

        return total;
      }

    main() {
        int values[SIZE], i;

        for (i = 0;  i < SIZE; i++)
            values[i] = i;

        printf("total = %d\n", sum(values, SIZE));
      }


...previousup (conts)next...



About this document:

Produced from the SGML: /home/isd/public_html/_course_crash_in_c/_reml_grp/index.reml
On: 3/3/2003 at 17:43:41
Options: reml2 -i noindex -l long -o html -p multiple