5 functions

53
CMPE-013/L: “C” Programmin riel Hugh Elkaim – Spring 2012 CMPE-013/L Functions Gabriel Hugh Elkaim Spring 2012

Upload: hey-hey

Post on 04-Oct-2015

228 views

Category:

Documents


0 download

DESCRIPTION

its goood

TRANSCRIPT

Why Smart Products?

CMPE-013/L

Functions

Gabriel Hugh ElkaimSpring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

drink(){ ... be_merry(); return;}

be_merry(){ ... return;}

eat(){ ... return;}

main(){ ... eat(); ... drink(); ...}FunctionsProgram Structure

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 20122The idea behind functions is that they allow you to modularize your code by breaking it up into several sub-programs that may be called over and over again in the course of a program's execution. As an added benefit, well written functions may be reused in other programs as well.

DefinitionFunctionsWhat is a function?

Functions are self contained program segments designed to perform a specific, well defined task.All C programs have one or more functionsThe main() function is requiredFunctions can accept parameters from the code that calls themFunctions usually return a single valueFunctions help to organize a program into logical, manageable segments

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 20123All functions can be thought of as small, self-contained programs that are designed to work with other functions in the context of a larger program. A well written function should perform a specific, well defined task so that it is easier to develop and debug.

The main() function is special in that it is required in every C program, and it must have the name main(). Other functions will be called from within the main() function.

The purpose of most functions is to process information passed to it by the part of the program that called it, though some functions take no parameters at all. In general, functions only return a single value.

Functions in C are conceptually like an algebraic function from math class

If you pass a value of 7 to the function: f(7), the value 7 gets "copied" into x and used everywhere that x exists within the function definition: f(7) = 72 + 4*7 + 3 = 80FunctionsRemember Algebra Class?

f(x) = x2 + 4x +3

Function Name

Function Parameter

Function Definition

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

SyntaxFunctionsDefinitionstype identifier(type1 arg1,,typen argn){ declarations statements return expression;}Data type ofreturn expression

Name

Parameter List(optional)

Return Value (optional)

Header

Body

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Example A more efficient version

ExampleFunctionsFunction Definitions: Syntax Examplesint maximum(int x, int y){ int z; z = (x >= y) ? x : y; return z;}int maximum(int x, int y){ return ((x >= y) ? x : y);}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 20126Here are two versions of the same function. They both return the maximum value between x and y, but the first one is more useful for illustrating the possible components of a function. In the first one, we show how to declare a local variable (scope will be discussed shortly).The second one is more efficient since it doesn't require the local variable z. The second one uses 6 fewer bytes of program memory than the first one data memory usage is the same. z is temporarily allocated on the stack so no "extra" RAM is required, but more program code is needed to manipulate z.

Description:(1) The first line of the function is known as the function header. The header contains all of the information about how a program can interface with a function. It lists any parameters that the function will accept, along with their respective data types. It also defines what type of data is returned by the function. In this case, the function will accept two parameters, both of which are integers. Note that we cannot declare the parameters as a list of variables after one data type such as (int x, y) which was perfectly legal to do when declaring ordinary variables. In the header, each parameter variable must be individually listed after its data type. This function also returns an integer value.

(2) In the first function, we declare a local integer variable z to use within the scope of this function. z is only accessible within this function, as are x and y.

(3) In both functions, we use the conditional operator ?: to determine which parameter has the largest value. The first function assigns the maximum value to z first, then it returns the value of z to the program that called the function. In the second version of this function, we bypass the need to use a local variable and simply return the value of the expression directly.

SyntaxFunctionsFunction Definitions: Return Data TypeA function's type must match the type of data in the return expression

type identifier(type1 arg1,,typen argn){ declarations statements return expression;}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

ExampleFunctionsFunction Definitions: Return Data TypeA function may have multiple return statements, but only one will be executed and they must all be of the same typeint bigger(int a, int b){if (a > b)return 1;elsereturn 0;}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 20128While a function can only return one value via the return statement, you may have multiple return statements that are conditionally executed. In this example, only one of the two return statements will be executed. If a is greater than b, then the first return statement will return the value 1. If a is less than or equal to b, then the second return statement will return the value 0.

Examplevoid identifier(type1 arg1,,typen argn){ declarations statements return;}

return; may be omitted if nothing is being returnedFunctionsFunction Definitions: Return Data TypeThe function type is void if:The return statement has no expression The return statement is not present at allThis is sometimes called a procedure function since nothing is returned

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Syntaxtype identifier(type1 arg1,,typen argn){ declarations statements return expression;}FunctionsFunction Definitions: ParametersA function's parameters are declared just like ordinary variables, but in a comma delimited list inside the parenthesesThe parameter names are only valid inside the function (local to the function)

Function Parameters

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012FunctionsFunction Definitions: ParametersParameter list may mix data typesint foo(int x, float y, char z)Parameters of the same type must be declared separately in other words:int maximum(int x, y) will not workint maximum(int x, int y) is correct

Exampleint maximum(int x, int y){ return ((x >= y) ? x : y);}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012FunctionsFunction Definitions: ParametersIf no parameters are required, use the keyword void in place of the parameter list when defining the function

Example

type identifier(void){declarationsstatementsreturn expression;}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 201212The parameter names declared in the function header are local to the function, meaning that they are not valid anywhere outside of the function. Their names may be the same as other variables in the main program or in other functions, though they don't need to be (and usually aren't).If a function doesn't take any parameters, the parameter list must be replaced by the keyword void.

Function Call SyntaxFunctionsHow to Call / Invoke a FunctionNo parameters and no return valuefoo();No parameters, but with a return valuex = foo();With parameters, but no return valuefoo(a, b);With parameters and a return valuex = foo(a, b);

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012FunctionsFunction PrototypesJust like variables, a function must be declared before it may be usedDeclaration must occur before main() or other functions that use itDeclaration may take two forms:The entire function definitionJust a function prototype the function definition itself may then be placed anywhere in the program

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Function prototypes may be take on two different formats:An exact copy of the function header:

Like the function header, but without the parameter names only the types need be present for each parameter:FunctionsFunction Prototypes

Example Function Prototype 1int maximum(int x, int y);

Example Function Prototype 2int maximum(int, int);

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Example 1

FunctionsDeclaration and Use: Example 1int a = 5, b = 10, c;

int maximum(int x, int y){ return ((x >= y) ? x : y);}

int main(void){ c = maximum(a, b); printf("The max is %d\n", c)}

Function is declared and defined before it is used in main()

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Example 2

FunctionsDeclaration and Use: Example 2int a = 5, b = 10, c;

int maximum(int x, int y);

int main(void){ c = maximum(a, b); printf("The max is %d\n", c)}

int maximum(int x, int y){ return ((x >= y) ? x : y);}

Function is defined after it is used in main()

Function is declared with prototype before use in main()

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012FunctionsPassing Parameters by ValueParameters passed to a function are passed by valueValues passed to a function are copied into the local parameter variablesThe original variable that is passed to a function cannot be modified by the function since only a copy of its value was passed

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Example

FunctionsPassing Parameters by ValueThe value of a is copied into x.The value of b is copied into y.The function does not change the value of a or b.

int a, b, c;

int foo(int x, int y){ x = x + (++y); return x;}

int main(void){ a = 5; b = 10; c = foo(a, b);}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

ExampleFunctionsRecursionA function can call itself repeatedlyUseful for iterative computations (each action stated in terms of previous result)Example: Factorials (5! = 5 * 4 * 3 * 2 * 1)long int factorial(int n){if (n = y) ? x : y);}

int maximum(int x, int y){ return ((x >= y) ? x : y);}

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

Lab Exercise 8Functions

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Exercise 08 Functions Open the lab Project:

On the class websiteExamples -> Lab8.zip

1Open MPLABX and select Open Project Icon (Ctrl + Shift + O)Open the Project listed above.If you already have a project open in MPLAB X, close it by right clicking on the open project and selecting Close

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 201231If you are not familiar with using MPLAB, simply follow the instructions in the handout, or follow along as I go through the demo. First, if you already have a project open, please close it by selecting File> Close Workspace. Now, we need to open the lab 1 workspace, so select Open Workspace from the Fle menu and navigate to the class directory and workspace file shown in the box at the top of the slide.

Exercise 08Functions/*############################################################################# STEP 1: Write two function prototypes based on the following information:# + Function Name: multiply_function()# - Parameters: int x, int y# - Return type: int# + Function Name: divide_function()# - Parameters: float x, float y# - Return type: float ############################################################################*/

int multiply_function( int x, int y); //multiply_function() prototype

float divide_function( float x, float y ); //divide_function() prototypeSolution: Step 1

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Exercise 08Functions/*############################################################################# STEP 2: Call the multiply_function() and divide_function().# (a) Pass the variables intVariable1 and intVariable2 to the# multiply_function().# (b) Store the result of multiply_function() in the variable "product".# (c) Pass the variables floatVariable1 and floatVariable2 to the# divide_function().# (d) Store the result of divide_function() in the variable "quotient".############################################################################*/

//Call multiply_function product = multiply_function( intVariable1 , intVariable2 );

//Call divide_functionquotient = divide_function( floatVariable1 , floatVariable2 ); // intQuotient will be 0 since it is an integerintQuotient = divide_function( floatVariable1 , floatVariable2 );Solution: Step 2

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Exercise 08Functions

/*############################################################################# STEP 3: Write the function multiply_function(). Use the function prototype# you wrote in STEP 1 as the function header. In the body, all you# need to do is return the product of the two input parameters (x * y)############################################################################*///Function Headerint multiply_function( int x, int y){ return (x * y); //Function Body}

/*############################################################################# STEP 4: Write the function divide_function(). Use the function prototype# you wrote in STEP 1 as the function header. In the body, all you# need to do is return the quotient of the two input parameters (x / y)############################################################################*///Function Headerfloat divide_function( float x, float y ){ return (x / y); //Function Body}Solution: Steps 3 and 4

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Exercise 08ConclusionsFunctions provide a way to modularize codeFunctions make code easier to maintainFunctions promote code reuse

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012Questions?

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 201236

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012

CMPE-013/L: C ProgrammingGabriel Hugh Elkaim Spring 2012