Function Return Values; Identifier Attributes

Tom Kelliher, CS17

Mar. 20, 1996

Function Return Values

Recall the pow function:

double pow(double x, double y);
Someone had to define it:
double pow(double x, double y)
{
   double value;

   ...

   return value;
}
So we could call it:
z = pow(x, 2.0) + pow(y, 3.0);
Relationship between call and return?

Some function termination conditions:

Example 1

#include <iostream.h>

// Prototype
int getInput(void);

int main()
{
   int i;
   int j;

   i = getInput();
   j = getInput();

   cout << "i: " << i << endl;
   cout << "j: " << j << endl
   return 0;
}

int getInput(void)
{
   int val;

   cout << "Enter an integer: ";
   cin >> val;

   return val;
}

Sample output:

Enter an integer: 39
Enter an integer: -83
i: 39
j: -83

Example 2

void printInstructions(void)
{
   char c;

   cout << "Would you like instructions (y or n)? ";
   cin >> c;

   if (c != 'y')
      return;

   cout << "HaHa!!! There are no instructions available!!!\n";
   cout << "You don't need instructions anyway.\n";
}

Identifier Attributes

Identifier: variable, symbolic constant, function, etc.

Scope:

The region in which an identifier exists.

Visibility:

The accessibility of an identifier.

An identifier may be in scope, but not visible:

int i = 1;

f()
{
   cout << i << endl;
}

g()
{
   double i = 2.0;

   cout << i << endl;

   {
      int i = 3;

      cout << i << endl;
   }

   cout << i << endl;
}

Program Fragment Example

// beginning of file
int a;

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

int c;

void main()
{
   int d;

   {  int a;
      ...
      a;

      ::a;
   }

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

Global scope resolution operator: ::.

Variable, symbolic constant lifetime:

The time, during program execution, that memory (RAM) is allocated for the variable or constant.
Lifetime types:

Program Design Problem

Design a program which computes factorials. The program should accept positive integers from the user, asking them if they want to continue, and output the factorial of the input.



Thomas P. Kelliher
Tue Mar 19 14:17:00 EST 1996
Tom Kelliher