next up previous contents index
Next: Header files Up: Subroutines, functions, and libraries Previous: Subroutines, functions, and libraries   Contents   Index


Defining subroutines

The declaration of subroutines in C is a bit different than in Perl - in C, you must declare both the return type and the types of arguments accepted.
  int my_neat_sub(int arg1, float arg2) {
     do stuff stuff here;
  }
which accepts two arguments (an int arg1 and a float arg2), and returns an int. This will be called in your program as
  int return_code, arg1 = 11;
  float arg2 = 3.14;
  return_code = my_neat_sub(arg1, arg2);
The compiler will check that the types of arguments used in the calling routine agree with those in the subroutine declaration.

There are two conventions used in defining subroutines in a program. One is at the top of the program:

  #include <stdio.h>
  int sub1(int arg1, float arg2) {
     do stuff stuff here;
  }
  void sub2(char arg2) {
     do stuff stuff here;
  }
  int main(void) {
     do things here;
     return 0;
  }
The other way is to place them after the main routine, which has the advantage of placing the main routine near the top of the file, allowing easier editing access. If done this way, though, the subroutines must be declared at the top of the file, so that the compiler knows about them if they are accessed in the main routine:
  #include <stdio.h>
  int sub1(int, float);
  void sub2(char);
  int main(void) {
     do things here;
     return 0;
  }
  int sub1(int arg1, float arg2) {
     do stuff stuff here;
  }
  void sub2(char arg2) {
     do stuff stuff here;
  }
Similar considerations regarding the scope of variables apply to C as they did with Perl - variabled declared within a subroutine are local to that subroutine, and are not accessible outside the routine. For example,
#include <stdio.h>
void sub(int);
int main(void) {
  int age = 22;
  printf("In the main routine, age is %d\n", age);
  sub(11);
  return 0;
}
void sub(int in) {
  int age = 33;
  printf("In the subroutine, you passed in %d, and age is %d\n", in, age);
}
will print out
In the main routine, age is 22
In the subroutine, you passed in 11, and age is 33

next up previous contents index
Next: Header files Up: Subroutines, functions, and libraries Previous: Subroutines, functions, and libraries   Contents   Index