# Review and Reinforcement: Simple Functions

Tom Kelliher, CS18

Feb. 12, 1996

# Introduction

Fundamental control mechanisms:

• Sequence
• Selection
• Repetition

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

• Function declarations
• Function definitions
• Functions calls

The one required function

## Function Declarations

• Return type
• Formal parameter list
• Purpose
• Placement --- scope
• Matching the definition

## Function Calls

• Declaration in scope
• Return type match?
• Number and types of actual arguments must match prototype

## Function Definitions

• Number and types of actual arguments must match prototype
• Return type must match prototype
• Details of the function are defined

# Value Return Mechanism

The return statement:

• In a function with void type --- return;
• In all other functions --- return expr ;

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
return;
}

int addOrSubtract(int op, int val1, int val2)   // definition
{
switch (op)
{
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;
}
}
```

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