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)); } |
...previous | up (conts) | next... |