Review and Reinforcement: Simple Functions

Tom Kelliher, CS18

Feb. 12, 1996

Introduction

Fundamental control mechanisms:

Where do functions fit in?

Modular programming:

Organizing a program into small, independent modules that are separately named and indivdually addressable program elements. These modules are integrated to become a software system that satisfies the problem requirements.

Elements Related to Functions

The one required function

Function Declarations

Function Calls

Function Definitions

Value Return Mechanism

The return statement:

Must a void function have a return statement?

Is there any restriction on where return is placed?

return in main vs. any other function

Example:

int addOrSubtract(int, int, int);  // declaration

void main()
{
   // call before definition
   cout << addOrSubtract(ADD, 45, 65) << endl;
   return;
}

int addOrSubtract(int op, int val1, int val2)   // definition
{
   switch (op)
   {
      case ADD:
         return val1 + val2;
         break;
      case SUB:
         return val1 - val2;
         break;
      default:
         error("Invalid op");
         break;
   }
}

Attributes of Identifiers

Value

The data (integer, floating point number, character, address, etc.) associated with an identifier (rvalue).

Location

The main memory storage associated with an identifier (lvalue).

Constants have no location

Scope

The region of a program in which an identifier is valid.

Types: file or block

Example:

// beginning of file
int i;

void f(void)
{
   int j;
   ...
}

int k;

void main()
{
   int l;

   if (thisOrThat)
   {  int m;
      ...
   }

   int n;
   ...
}
// end of file

Visibility

The accessibility of an identifier from a particular statement of the program. An identifier must first be in scope before we can consider if it is visible or not.

Making a global identifier visible: the global operator ::

Example:

int i;

void f()
{  int i;
   i = 3;
   ::i = 4;

   {  int i;
      i = 5;
      ::i = 6;
   }
}

Lifetime

The period of time during which a memory location is associated with the identifier.

Types: static, local, or dynamic

Example:

int i;

int* f()
{
   int j;
   static int k;
   int* p;

   p = new int;
   return p;
}

main()
{
   int* q;

   q = f();
   delete q;
}



Thomas P. Kelliher
Fri Feb 9 08:01:40 EST 1996
Tom Kelliher