Week 6

Ch. 6 Functions

A function is a self-contained block of code that is called upon for a specific purpose or task. Programmer defined functions help with program readability, code reuse, and program design. They help break a problem down into small manageable pieces.
So far, the only function we have been defining is main(), but most C++ applications actually consist of many functions.

  • Function Definition
  • Function Call
  • Function Prototype

Function Definition

Syntax:
returnType functionName( parameter_list) {
  //
  // function body
  //
}
******************************************

Function Definition example:

int sum(int a, int b) {
  return(a+b);
}

Function Call

int main() {

  int result = sum(1,2);
  
  int a=1, b=2;
  cout << "sum: " << sum(a,b) << endl;
  return(0);
}

Function Prototype

Syntax:
returnType functionName( parameter_list );
******************************************

Function Prototype example:

int sum(int,int);   // func prototype

int main() { ... sum(1,2); // func call ...}

int sum(int a, int b) { return(a+b); } // func definition

Return Types and void Functions

Pass By Value

Pass By &Reference

Function Overloading

Default Arguments

Local Vars / Global Vars / Static Vars

cstdlib exit()