functions and program structure

32
Functions and Program Structure Chapter 4

Upload: walda

Post on 08-Jan-2016

49 views

Category:

Documents


1 download

DESCRIPTION

Chapter 4. Functions and Program Structure. Introduction. Functions break large computing tasks into smaller ones Appropriate functions hide details of operation from parts of the program that don’t need to know about them Thus clarifying the whole - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Functions and Program Structure

Functions and Program Structure

Chapter 4

Page 2: Functions and Program Structure

Introduction

Functions break large computing tasks into smaller ones Appropriate functions hide details of operation from parts of

the program that don’t need to know about them Thus clarifying the whole And easing the pain of making changes

C has been designed to make functions efficient and easy to use

C programs generally consist of many small functions rather than a few big ones

A program may reside in one or more source files

Page 3: Functions and Program Structure

Basics of Function

return-type function-name (argument declarations) {

declarations and statements

} Various parts may be absent A minimal function is:

dummy( ) { } Which does nothing and returns nothing Sometimes useful as a place holder during program

development Functions declaration must be used

Page 4: Functions and Program Structure

Basics of Function Contd.

A program is just a set of definitions of variables and functions

Communication between the functions is by Arguments Values returned by the functions, and Through external variables

The functions can occur in any order in the source file

Page 5: Functions and Program Structure

Basics of Function Contd.

The source program can be split into multiple files

The return statement is the mechanism for returning a value from the called function to its caller

return expression;

Page 6: Functions and Program Structure

Basics of Function Contd.

The calling function is free to ignore the returned value

There need be no expression after return In that case, no value is returned to the caller Control also returns to the caller with no value

when execution "falls off the end", i.e., “}”

Page 7: Functions and Program Structure

External Variable External variables are globally accessible They provide an alternative to function

arguments and return values for communicating between functions

If a large number of variables must be shared among functions, external variables are more convenient and efficient than long argument list

Page 8: Functions and Program Structure

External Variable Contd.

However, this reasoning should be applied with some caution

External variables are also useful because of their greater scope and lifetime

Internal variables come into existence when the function is ended

If two functions must share some data, yet neither calls the other, it is often most convenient to use external variables rather than passed in and out via arguments

Page 9: Functions and Program Structure

External Variable: Where needed?#define MAXVAL 100

int sp = 0;

double val [MAXVAL];

void push (double f){

if (sp < MAXVAL)val [sp++] = f;

else printf (“Overflow”);

}

double pop (){

if (sp > 0)

return val [--sp];

else {

printf (“Under flow”);

return 0.0;

}

}

Page 10: Functions and Program Structure

Scope Rules

The source text of the program may be kept in several files

The concerns are Variable declaration

Properly declared Only one copy Initialization

The scope of a name is that part of the program within which the name can be used

Page 11: Functions and Program Structure

Scope Rules Contd.

For local variables For external variables or a function (from that

point) If an external variable is to be referred to

before it is defined, or if it is used in different source file from where it is

used then extern declaration is mandatory No storage allocation

Page 12: Functions and Program Structure

Extern Declaration

There must be only one definition of an external variable among all the files

There may also be extern declaration in the file containing definition

Array size must be specified with the definition but are optional with an extern declaration

Initialization of an external variable goes only with definition

Page 13: Functions and Program Structure

Header Files

If certain functions will be pretty common and be useful to many programs a head Then those functions can be kept in a header file

(extension is .h) and put in the library directory Think about the necessity of the functions defined

in stdio.h

Page 14: Functions and Program Structure

Static Variables

Unlike automatic variables static variables remain in existence between functions calls

Static variables provide private, permanent storage within a single function

The static variable is initialized only the first time the block is entered

static int i = 0;

Page 15: Functions and Program Structure

Register Variablesregister int x;

A register declaration advises the compiler that the variable will be heavily used

Register variables are to be placed in machine registers Result in faster programs The index of the innermost loop can be register variable

It is not possible to take the address of a register variable

It specific restrictions on number and types of register variables vary from machine to machine

Page 16: Functions and Program Structure

Block Structure

Variables can be declared in any block “{}” Variables declared in this way hide any identically

named variables in outer block An automatic variable declared and initialized in a

block is initialized each time the block is entered The static variable is initialized only the first time the

block is entered Automatic variables, including formal parameters

also hide external variables and functions of the same name

Page 17: Functions and Program Structure

Initialization

Automatic and register variables External and static variables Initializing arrays

Page 18: Functions and Program Structure

Recursive Function

A function may call itself When a function call itself recursively, each

invocation gets a fresh set of all the automatic variables

Recursion may provide no saving in storage nor will be faster Because of stack entry

But recursive code is more compact and often much easier to write Recursion is especially convenient for recursively defined

data structures (tree)

Page 19: Functions and Program Structure

Criteria of Recursive

Function A terminating condition Recursive definition

Page 20: Functions and Program Structure

Factorial has a recursive

definitonint facti(int n){

int i, product = 1;

for(i = 2; i <= n; i++)

product *= i;

return product;

}

int factr(int n){

if(n == 0)

return 1; //terminating condition

else //recursive definition

return n*factr(n-1);

}

Page 21: Functions and Program Structure

Itoavoid itoa (int n, char s[ ]){

if ((sign = n) < 0)n = -n; /* make it positive

*/

i = 0;do{

s [i++] = n % 10; + ‘0’;} while ((n /= 10) > 0);if (sign < 0) s [i++] = ‘-’;s [i] = ‘\0’;reverse (s);

}

void itoa(int n, char s[]){static int i;

if(n/10){itoa(n/10,s); //recursive definition

s[i++] = n % 10 + '0';s[i + 1] = 0;

}else{

s[i++] = n % 10 + '0';//terminating

return;}

}

Page 22: Functions and Program Structure

int binsearch(int x, int v[ ], int n){int low, high, mid;low = 0;high = n -1;while(low <= high){

mid = (low + high)/2;if (x < v[mid])

high = mid – 1;else if(x > v[mid])

low = mid + 1;else return mid;

}return -1;

}

int bsearch(int x, int v[], int low, int high){static mid;

if(low > high) return -1;

mid = (low + high)/2;if(x < v[mid])

return bsearch(x, v,low,mid-1);

else if(x > v[mid])return bsearch(x, v, mid + 1,

high);else

return mid;}

Page 23: Functions and Program Structure

The C Preprocessor

The first step in compilation File inclusion Macro substitution Conditional inclusion

Page 24: Functions and Program Structure

File Inclusion

#include “filename” #include <filename>

Page 25: Functions and Program Structure

Macro Substitution

#define name replacement text Normally the replacement text is the rest of

the line A long definition can be continued to several

lines by placing a \ Array declaration

#define ARRAYLIMIT 20

char str[ARRAYLIMIT];

Page 26: Functions and Program Structure

Macro Substitution Contd.

#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))

x = MAX(p+q, r+s); There is no need to define different MAX for

different data types

Page 27: Functions and Program Structure

Macro Substitution Contd.

#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))

x = MAX(p+q, r+s); There is no need to define different MAX for

different data types

Page 28: Functions and Program Structure

Macro Substitution Contd.

#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))

x = MAX(p+q, r+s); There is no need to define different MAX for

different data types

Page 29: Functions and Program Structure

Macro Substitution Contd.

MAX(i++, j++); //wrong

#undef getchar

int getchar(){

}

Page 30: Functions and Program Structure

Macro Substitution Contd.

# in the replacement text#define DPRINT(EXP) printf(#EXP “ = %g\n”, EXP)

DPRINT(x/y); is expanded

printf(“x/y” “ = %g\n”, x/y);

The two strings are concatenated like

printf(“x/y = %g\n”, x/y);

Page 31: Functions and Program Structure

Macro Substitution Contd.

The ## provides a way to concatenate actual arguments during macro expansion

#define CON(FRONT, BACK) FRONT##BACK CON(12, 34)

Page 32: Functions and Program Structure

Conditional Inclusion

#if !defined(HDR)

#define HDR …..\

….

#endif