+ All Categories
Home > Documents > C Programming Lecture 7 Functions. Structured Programming b Keep the flow of control in a program as...

C Programming Lecture 7 Functions. Structured Programming b Keep the flow of control in a program as...

Date post: 17-Dec-2015
Category:
Upload: sandra-morris
View: 219 times
Download: 0 times
Share this document with a friend
Popular Tags:
20
C Programming C Programming Lecture 7 Lecture 7 Functions Functions
Transcript

C ProgrammingC Programming

Lecture 7Lecture 7

FunctionsFunctions

Structured ProgrammingStructured Programming

Keep the flow of control in a Keep the flow of control in a program as simple as program as simple as possible.possible.

Use Use top-down designtop-down design..• Keep Keep decomposingdecomposing (also known as (also known as factoringfactoring) a problem into ) a problem into smaller problems until you have smaller problems until you have a collection of small problems a collection of small problems that you can easily solve.that you can easily solve.

Top-Down Design Using Top-Down Design Using FunctionsFunctions

C programs normally consist C programs normally consist of a collection of of a collection of user-user-defineddefined functions. functions.• Each function solves one of the Each function solves one of the small problems obtained using small problems obtained using top-down design.top-down design.

• Functions Functions callcall or or invokeinvoke other other functions as needed.functions as needed.

Function Definitions, Function Definitions, Prototypes, and Calls Prototypes, and Calls

#include <stdio.h>

void prn_message(void); /* fct prototype *//* tells the compiler that this *//* function takes no arguments */

int main(void) /* and returns no value. */{ prn_message(); /* fct invocation */}

void prn_message(void) /* fct definition */{ printf(“A message for you: “); printf(“Have a nice day!\n”);}

Form of a Function Form of a Function DefinitionDefinition

type function_name ( parameter type list ){ declarations statements}

Some TerminologyHeader: Everything before the first brace.Body: Everything between the braces.Type: Type of the value returned by the function.Parameter List: A list of identifiers that provide information

for use within the body of the function. Also called formal parameters.

The The returnreturn Statement Statement When a return statement is When a return statement is executed, program control is executed, program control is immediately passed back to the immediately passed back to the calling environment.calling environment.• If an expression follows the keyword If an expression follows the keyword returnreturn, the value of the expression , the value of the expression is returned to the calling is returned to the calling environment as well.environment as well.

return;return;return expression;return expression;

If There is If There is No returnNo return

Control is passed back to the Control is passed back to the calling environment when the calling environment when the closing brace of the bodyclosing brace of the body is is encountered.encountered.• Known as “Known as “falling of the endfalling of the end.”.”

Exit Status and Exit Status and returnreturn Verus Verus exit( )exit( )

In main() In main() eithereither return expr;return expr;

oror

exit(expr);exit(expr);

will return an integer value to the will return an integer value to the operating system.operating system.

In functions other than main(), In functions other than main(), the effects of the effects of returnreturn and and exitexit are are differentdifferent..

return exprreturn expr Versus Versus exit(expr)exit(expr)

return exprreturn expr returns the value returns the value of of exprexpr to the to the calling calling functionfunction..

exit(expr)exit(expr) always causes the always causes the program to terminateprogram to terminate and and returns an returns an exit statusexit status to the to the operating systemoperating system. The value . The value in in exprexpr is the is the exit statusexit status..

Demo Program – Using a Function to Calculate the Minimum of 2 Values

#include <stdio.h>

int min(int a, int b);

int main(void){ int j, k, m; printf(“Input two integers: “); scanf(“%d%d”, &j, &k); m = min(j, k); printf(“\nOf the two values %d and %d, “ “the minimum is %d.\n\n”, j, k, m); return 0;}

int min(int a, int b){ if (a < b) return a; else return b;}

Function PrototypesFunction Prototypes

A function prototype tells the A function prototype tells the compiler:compiler:• The The numbernumber and and typetype of of argumentsarguments that that are to be passed to the function.are to be passed to the function.

• The The typetype of the of the valuevalue that is to be that is to be returnedreturned by the function. by the function.

General Form of a Function General Form of a Function PrototypePrototype

typetype function_namefunction_name( ( parameter type listparameter type list););

Examples of Function Examples of Function PrototypesPrototypes

doubledouble sqrtsqrt((doubledouble););

The parameter list is typically a The parameter list is typically a comma-separated list of types. comma-separated list of types. Identifiers are optionalIdentifiers are optional..

voidvoid f( f(char char cc, , int int ii);); is equivalent tois equivalent to voidvoid f( f(charchar, , intint););

The Keyword void The Keyword void

voidvoid is used if: is used if:• A function takes A function takes no argumentsno arguments..• If If no value is returnedno value is returned by the by the function.function.

Function InvocationFunction Invocation

As we have seen, a function is As we have seen, a function is invokedinvoked (or (or calledcalled) by writing ) by writing its name and an appropriate its name and an appropriate list of arguments within list of arguments within parentheses.parentheses.• The The arguments must matcharguments must match in in numbernumber and and typetype the parameters the parameters in the parameter list of the in the parameter list of the function definition.function definition.

Call-by-ValueCall-by-Value

In C, all arguments are In C, all arguments are passed call-by-value.passed call-by-value.• This means that each argument is This means that each argument is evaluated, and its evaluated, and its valuevalue is used is used in place of the corresponding in place of the corresponding formal parameterformal parameter in the in the calledcalled function.function.

Demonstration Program for Call-by-Value#include <stdio.h>

int compute_sum(int n);

int main(void){ int n = 3, sum; printf(“%d\n”, n); /* 3 is printed */ sum = compute_sum(n); printf(“%d\n”, n); /* 3 is printed */ printf(“%d\n”, sum); return 0;}

int compute_sum(int n){ int sum = 0;

for (; n > 0; --n) /* in main(), n is unchanged */ sum += n; printf(“%d\n”, n); /* 0 is printed */ return sum;}

#include <stdio.h>#include <stdlib.h>

list of function prototypes

int main(void){ . . .}

int max(int a, int b){ . . .}

int min(int a, int b){ . . .}

void prn_random_numbers(int k){ . . .}

Standard Style for Function Definition Order

#include <stdio.h>#include <stdlib.h>

int max(int a, int b){ . . .}

int min(int a, int b){ . . .}

void prn_random_numbers(int k){ . . .}

int main(void){ . . .}

“Alternate Style for Function Definition Order

We will use thestandard style.

Common Programming Common Programming ErrorsErrors

If f() is a function and v is If f() is a function and v is a variable, then the function a variable, then the function call f(call f(vv) ) cannot cannot change the change the value in the variable value in the variable vv..• A common error for beginners is A common error for beginners is assuming the the value in v can assuming the the value in v can be changed by a function call be changed by a function call such as f(v).such as f(v).

StyleStyle

Avoid naming functions you write Avoid naming functions you write with the same name as system with the same name as system functions.functions.• Example: read, write, printExample: read, write, print

Minimize the number of return Minimize the number of return statements in a given function.statements in a given function.

Use names for parameters that Use names for parameters that clearly identify their purpose.clearly identify their purpose.


Recommended