Review:   The parameter passing mechanism used in C

  • Parameter passing mechanism in C:

      • C programs always use the pass-by-value parameter passing mechanism

  • Note:

      • Some expressions in C returns a value of an address

        Example:

          int A[10];
        
          A = the address of the location of the array A 

      • When the value of an address is passed (= copied), the effect is like pass-by-reference !

C struct variables are passed-by-value to a function

  • In C, an struct typed variable is passed-by-value

    I.e.:

      • All member fields inside a struct variable is copied into the formal parameter of the function call

  • Remember:

      • Arguments that are passed-by-value will not get updated by the function call !

  • Therefore:

      • Struct typed arguments will not be changed by a function call (just like arguments of a basic data type)

  • I will demonstrate this fact using a example C program next

Example C program that demonstrate struct typed parameters are passed-by-value

struct BankAccount  // I define struct here for brevity
{
   int    accNum;
   double balance;
};

// x is passed-by-value
void f( struct BankAccount x )
{
   x.accNum  = 888; 
   x.accNumx.balance = 9999.0;  // Updates copy
}

int main(int argc, char *argv[])
{
   struct BankAccount a;

   a.accNum  = 123;
   a.balance = 1000.0;

   printf("a = (%d, %f)\n", a.accNum, a.balance); // 123, 1000.0

   f(a); // a = the entire struct, therefore: C passes "a" by value 

   printf("a = (%d, %f)\n", a.accNum, a.balance); // a is unchanged !
} 

DEMO: demo/C/set2/struct-param.c (also check out: struct_param.java)