Defining a function (= method) in C
 

  • Syntax to define a function:

        returnType  funcName( parameters )              
        {
           // Function body
           Local variable definitions
      
           Statements
        }
      

  • A function definition cannot appear inside another function

Comment:   a function definition in C has similar syntax as in Java

Difference:   C does not use access qualifiers (such as public, private, etc)

Example of a function definition and calling a function
 

#include <stdio.h>

int f(int a, int b)  // Function definition 
{
   return(a*a + b*b);
}

int main(int argc, char *argv[])
{
   int x = 3, y = 4;
   int z;

   z = f(x,y);     // Function call 
   printf("%d^2 + %d^2 = %d\n", x, y, z);
}  

The syntax of a function call in C is almost identical to Java

Difference:   C does not use class prefix (Math.sin(x)) or instance variable prefix (myAcc.deposit(100)) - only uses the function name

The parameter passing mechanism used in C

C only has the pass-by-value parameter passing mechanism:

#include <stdio.h>

void f(int x)  
{
   x = x + 1;
}

int main(int argc, char *argv[])
{
   int a = 4;

   printf("Before calling f(a), a = %d\n", a); // prints 4   
   f(a);
   printf("After  calling f(a), a = %d\n", a); // prints 4
}   

Since the value of the parameter variable is unchanged, we showed that C provides pass-by-value

Postscript: reference data type
 

  • Although C only has the pass-by-value parameter passing mechanism, C can achieve the effect of the pass-by-reference mechanism !!!

  • C has a very powerful reference data type that no other (non-C related) programming language provides....

  • This reference data type and its operators provide the C programmer the tools to achieve the effect of the pass-by-reference mechanism