0% found this document useful (0 votes)
72 views23 pages

Reading Assignment: K.N. King Sections 7.1, 7.2, 7.5 Sections 16.5, 18.2, 20.1

This document provides information about functions in C programming. It discusses what functions are, how to design functions, how functions are declared and defined, how function parameters work, how to call and pass arguments to functions, and more details about scopes in C. Key points include: - Functions allow a program to be divided into smaller pieces and abstract repeated code. - Functions should perform a single, well-defined task and have a small number of parameters. - A function declaration specifies the name, return type, and parameters while a definition also includes the body. - Parameters pass arguments by value, so changes to parameters don't affect the original arguments. - Arrays passed as arguments just pass

Uploaded by

SateeshReddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views23 pages

Reading Assignment: K.N. King Sections 7.1, 7.2, 7.5 Sections 16.5, 18.2, 20.1

This document provides information about functions in C programming. It discusses what functions are, how to design functions, how functions are declared and defined, how function parameters work, how to call and pass arguments to functions, and more details about scopes in C. Key points include: - Functions allow a program to be divided into smaller pieces and abstract repeated code. - Functions should perform a single, well-defined task and have a small number of parameters. - A function declaration specifies the name, return type, and parameters while a definition also includes the body. - Parameters pass arguments by value, so changes to parameters don't affect the original arguments. - Arrays passed as arguments just pass

Uploaded by

SateeshReddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Reading Assignment

K.N. King

Sections 7.1, 7.2, 7.5


Sections 16.5, 18.2, 20.1

141

Functions

Functions are a mechanism that allows a large program to be subdivided into


smaller and more manageable pieces.
Functions can be developed and tested separately.
A function abstracts code that is used many places in the program
It is easier to debug and maintain one copy of code in a function than to debug
and maintain many copies of the same code spread throughout the program
The parameters of a function are the link between the function and each
place that the function is used.

142

How to Design Functions


Identify computation of an expression that occurs at several places in the
program
Identify a group of statements that occur at several places in the program or
represent a sub*part of the solution
Identify the input values that are required to compute the expression
Identify the variables that a modified by the group of statements
Good Design - small number of parameters
Examples
math functions: sin, cos, sqrt, atan, log
vector functions: inner product, vector sum
string functions: change case, remove blanks

143

Functions Declaration and Definition


A function header specifies
The name of the function.
The type of value returned by the function.
The type and name of the parameters that the function accepts.

A function can be specified in a program in two ways.


A function declaration is a function header followed by a semicolon.
A function declaration is also called a function prototype
A function definition is a function header followed by the body of the function
enclosed in

and


The function declaration provides all the information that is required to use the
function.
Good Style: Every function should be declared or defined before it is used.

144

If a declaration is given for a function, the declaration must be consistent with


the definition of the function.
Good Technique: Always provide a function prototype at the start of a file for
any functions that must be used before they are defined so that the compiler
has complete information about the function at the point where it is used.
WARNING: If you fail to provide a function declaration before a function is
used, the compiler will guess default types for the value returned by the
function and the types of functions parameters.
If the compilers guess is wrong, you have an ERROR in your program.
Header files are used in C to provide function prototypes and related
declarations for functions that are defined and compiled separately.
Header files are traditionally named file-name.h

145

Function Declarationa
type-name functionName ( parameters ) ;

functionName is the name of the function.


type-name is the type of value returned by the function. Use void to indicate
that a function returns no value.
The parameters are optional, but the left and right parentheses are required.
Good Style: use an explicit void to indicate a function takes no parameters.
This declaration is a promise that somewhere else there will be a consistent
definition for the function.
Examples:

float random ( void ) ;


int maxmum( int X , int Y ) ;
double innerProduct( double A[], double B[], int size ) ;
void printTable( float table[], short tableSize ) ;

Function declarations are sometimes called function prototypes


146

Function Definition
type-name functionName ( parameters )


declarations
statements


A function definition has the same form as a function declaration except that the body
of code that implements the function is supplied.

Variables, types and constants declared within a function are local to the function a

The variables local to a function are created at the instant a function is called, exist
until the function returns, at which point they are destroyed.

Except for constants declared using #define

147

Function Parameters
The parameters of a function are a comma-separated list of declarations of
the form
Example:

type-name identifer
int K, double X, short A[]

The function parameter declaration specifies


The order in which the function expects to receive its parameters
The type of value associated with each parameter.
The name that will be used to refer to the parameter in the body of the function

148

Function Call & Function Arguments


A function is called by writing the name of the function followed by a list of
arguments enclosed in parentheses. If the function has no parameters, you
must use an empty set of parentheses ( ) .
WARNING: F is not the same as F(), F does not call the function.
The order in which the arguments are written is used to match the arguments
to the parameters of the function.
Each argument must be of a type that is compatible with the type of the
corresponding function parameter .
WARNING: Many C compilers do very little checking for correct parameter
passing when a function is called. gcc is better than most
Be very careful about
The type of each argument.
The order of arguments
That exactly the right number of arguments has been supplied

149

Arguments are Passed By Value


In C, the parameters of a function behave like variables that are local to the
function.
When the function is called, space is allocated for the parameters of the
function. Each argument is evaluated and the value of the argument is
assigned to the local parameter variable.
Changes (i.e. assignments) to the parameter variable do not affect the
corresponding argument, even if it is a variable.
The const qualifier can be used to indicate that the function is not intended to
change the value of the parameter variable.
Later well see other forms of parameter passing.

150

Parameter and Argument Example


int K = 3, J = 17 ;
float Y = 3.1, Z =123.45 ;
void testFunc( int I, float X )


...
I = 17 ;


testFunc( 7, 14.5 ) ;

14.5

testFunc( K, Y + Z ) ;

126.55

testFunc( J - K , Y*Y ) ;

14

9.61

151

Array Arguments to Functions




A special mechanism in C makes it easy to pass arrays as arguments to functions

An array parameter is declared like an array, except that the size of the array can be
omitted.
Example:

int A[], int B[100] , double xCoords[]

The function cant determine the size of an array argumenta so the size of the array
must be passed as an additional argument to the function.

Even is the size of an array parameter is specified (e.g. B in the example above), C
allows a compatible array of any size to be passed as the corresponding argument.

The argument corresponding to an array parameter is the name of an array without


any subscripts

If the parameter is a multidimensional array, the size in the first dimension may be
omitted, but all the size in all other dimensions must be specified.

sizeof wont give the right answer in this case


152

Array Argument Example


double xArray[ 1000 ] ;
int xCount ;

...
/* Counting the number of negative values in an array */
int count negatives(const double A[], const int aSize )


int count = 0 , J ;

if ( A[ J ]

for ( J = 0 ; J

aSize ; J++ )
0.0 )

count++ ;
return count ;


...
xCount = count negatives( xArray, 1000 ) ;

153

Function example
int power( int x, int n );
...
main()


int i = 2, j = 10, k;
...
k = power( i, j );
...


...
int power( int x, int n )


int result = 1;
while ( n--

> 0)

result = result * x;
return result;


154

return statement
return expression ;

The return statement is used to return a value from a function


expression is the value returned by the function.
The expression is optional, if it is omitted the function returns GARBAGE
If a function returns by running off the end of the function body it returns
GARBAGE
The type of the expression should be compatible with the return type
declared for the function.
WARNING: Many C compilers do not verify this compatability.
Using an expression statement, the value returned by a function can be
discarded.
Good Style: declare a function as returning void if it is not intended to return
a useful value
155

More on Scopes in C


The unit of compilation in C is a single source file

The body of each function introduces a distinct Local scope.


and

A local block scope is corresponds to the text enclosed in

Items declared in a local scope or a local block scope are only visible in that scope.


Each source file introduces a file scope containing all the types, data and functions
declared in that source file. Items declared in a source file outside of a function are
visible to all functions declared in the file.

The extern declaration prefix can be used to share declarations across source files.
The static declaration prefix can be used to limit the scope of a globally declared item
to the source file in which it occurs

Good Style: Use extern only when there is no other alternative for sharing variables
between files.
WARNING: Variables shared between files can lead to bad program structure and are
a major cause of errors.

156

Scope Example
int K;
void f( int K )


K = 1;


void g(void)


int K = 2;
157


if ( K

0)

int K;
K = 3;


K = 4;


void h(void)


K = 5;


extern & static


extern declaration
static declaration

The extern prefix on a declaration declares that the declared items exist in some other
file that is a part of the program
Normal usage: declare something in one source file and use extern in all other files
that need to access it
The static prefix on a declaration makes the declaration invisible outside of the file in
which it is declared. This can be used to hide declarations including function
declarations.
The static prefix also causes data items to have a lifetime that is the same as the
main program. Variables in a function declared with the static prefix retain their values
between calls of the function.

158

Scope example

/* File baz.c */

/* File foo.c */

char D ;

extern char D ;

int I ;

static int J;

extern void f(void ) ;

void f(void )

159

..

int M ;
static int K ;

..

char S ;

..
extern char S ;

Structuring C programs - .h and .c


A small C program is contained in a single source file.
Larger C programs are contained in several source files.
Technique: each logically separate part of the program should be represented
as two distinct source files:

fileName.h should define the interface to the part.


fileName.c should contain the implementation of the part
Typically the .h file contains only declarations of data items and functions
that are needed to use the part.
Typically the .c file contains private data declarations and the definitions of
the functions declared in the .h file
To use the part, only the .h file is required.
The .c file can be separately compiled.

160

Preview: #include
systemFileName

#include

#include localFileName

The #include directive causes the named file to be automatically included in


the source program at the point of the directive.
The first form is used to include files from the system libraries.
The second form is used to include files from the users directory.
localFileName can include directory path specifications.
WARNING: directory path specifications are not portable.
Examples:

#include <stdio.h>
#include "myInterface.h"
#include "C:\no\one\else\can\find\this\file.h"

161

Useful system library include files


assert.h

Diagnostic functions

stdio.h

All input and output functions

ctype.h

Character classification functions

string.h

All string processing functions

math.h

Mathematical functions, sin, sqrt, etc.

stdlib.h

Utility functions, conversion, storage allocation

stdarg.h

Variable argument list functions

setjmp.h

Non-local jumps

signal.h

Signals

time.h

Date and time functions

limits.h

Implementation defined limits

float.h

Implementation defined floating point

Include using #include

<fileName.h>
162

Program Structure Example

/* File foo.h */

/* File foo.c */

#include foo.h

extern char D ;

char D ;

extern int I ;

static int J;
int I ;

163

char S ;


extern void f(void ) ;

void f(void )

..

int M ;
static int K ;

..

extern char S ;


static int g( int N )

..


..

You might also like