+ All Categories
Home > Documents > 1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that...

1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that...

Date post: 21-Dec-2015
Category:
View: 217 times
Download: 1 times
Share this document with a friend
Popular Tags:
29
1 Introduction to Computers and Programming
Transcript

1

Introduction to Computers and Programming

Quick Review

What is a Function? A module of code that performs a specific job

3

Benefits of Functions

Experience has shown that the best way to develop and maintain large programs is to build it from smaller components or modules

In C, such modules are known as functions Each module is generally simpler and more

manageable than the entire program This concept is known as Divide and Conquer,

also with Hiding in the mix

Divide and Conquer

• Divide and Conquer: break large programs into a series of smaller functions.– Helps manage complexity– Makes it easier to build large programs– Makes is easier to debug programs

Hiding

• Abstraction: most of the time, you need to know what a function does, but not how it actually does it.– Also helps manage complexity.– You can use other people’s code, without understanding

how it works.

• If you have code that would appear more than once, can put it one function and call that function multiple times– Reduces length and complexity of code– Reduces likelihood of errors in code

Function Concepts (review)

• Function Prototype

• Function Definition

• Function Call

7

Rules of Prototyping

8

Function Prototype v. Definition

• The Function prototype and the function definition must include the same data types. However,– Prototype: you do not need to include the names of

parameters, but you must include the parameter data types.

• e.g. int square (int);

– Definition: you must include the name and data type of all parameters.

• e.g. int square (int y)

9

Naming your functions

• As with variables naming functions is important• You should give your functions names which

clearly describe what the function is doing– helps debugging

– helps others read your code

• Capitalize the first letter and the first initial of additional words– E.g. float CalculateTax( int iIncome ) ;

10

Good programming with functions

• A function should do one and only one useful action– If you see names for your function that suggest

multiple actions then it’s time to break it up into separate functions; for example,

CalculateTaxAndPrintReturnAndSaveFile(); -ugh

• If you do something more than once in a program, you should write a function for that action

11

More Good Programming

• If you have written a function to do something in one project, and you need to do the same action in another project, you should reuse the function

• Don’t make the inner workings of a function dependent on data in another part of the program or project (the function should only get data through its parameters)

12

Return Value Types

• You can only return one value from a function (there are ways around this which we will not cover)

• If you do not include a return-value type, it defaults to int.– Example:max (int, int);Is identical to:int max (int, int);

• It’s usually best to be explicit. I therefore recommend the second option.

13

Returning void

• void: means nothing

• A function that returns void therefore returns nothing.

• Hence, there is no need for a return statement.

• Example: void PrintIntro (int);

14

Parameter Data Types

• Unlike return values, you can pass as many parameters as you like.

• If you do not include a data type in the parameter list, it defaults to int.

• For example:negate ();

• Is identical to:int negate (int);

• Again, I recommend the more specific second option.

15

Warning

• Unlike declaring variables, you must specifically state the type for multiple variables other than ints– For example

TakeInTwoFloats( float x, y ) ;

will expect a float for x and int (default) for y! this would result in data loss (from float to int)

– Instead you must write

TakeInTwoFloats(float x, float y);

16

Passing void

• If you use void in the parameter list, the function accepts no parameters

• Example:void printIntro (void);

17

Another Example

#include <stdio.h>int maximum(int, int, int);

main(){

printf("Maximum is: %d\n", maximum(5, 7, 3));}int maximum(int x, int y, int z){

int max = x; if (y > max)

max = y;

if (z > max)max = z;

return max;}

Function Prototype: this function takes three ints, and returns one int.

Function Definition

Return statement

18

Argument Coercion

19

Argument Coercion

• Data is automatically forced to fit the data type described in the prototype. This may result in loss of data. – (see the TakeInTwoFloats example above)

• Works sort of like casting• This is generally not a good thing, so stick

with the prototype! – i.e. pass data of the type the function expects!

20

Example: Argument Coercion

• Given the following function prototype:

int square(int);• And, we invoke the function with a float value:

printf("%d ", square(5.7));• Because of argument coercion, 5.7 is truncated to

5.• We therefore have a loss of data

21

Understanding Scope

22

Scope

• Determines where the variable can be referenced in a program.

• By understanding scope, you can make your programs:– more modular– easier to debug

• Generally arises in discussions of global versus local variables

23

Global v. Local Variables

• Global: – A variable declared outside any function– Can be referenced by any function in the program

• Local: – A variable declared inside a function– Can only be referenced within that function.

• If you have a local variable in a function and a global variable with the same name, the local one is used

24

/* This program demonstrates global variables and scope */

#include <stdio.h>

void a (void);void b (void);

int x = 1; /* Global Variable */

main () {

printf ("In main, x equals: %d\n", x);

a();b();

printf ("In main, x equals: %d\n", x); return 0;}

void a (void) {int x = 100;printf ("In function (a), x equals: %d\n", x);

}

void b (void) {printf ("In function (b), x equals: %d\n", x++);

}

If you have a local variable and a global variable with the same name, the local one is used.

In main, x equals: 1

In function (a), x equals: 100

In function (b), x equals: 1

In main, x equals: 2

Example

25

Avoid Global Variables!

• Now that you know about global variables, never use them!

• Why?– If you use a global variable, any function can

modify it– This makes it extremely hard to track down

problems– Undermines the modularity of your programs

26

pass by value

• In c when a parameter is passed to a function and the variable is modified by that function, the value does not change upon return to the calling function (there are excpetions to this including passing arrays and passing pointer types)

• This is not true in all programming languages.

27

Document your functions (required!)

• An acceptable way is to precede the definition with the following:

/**************************************** * Name: CalculateTax * Params: floats for Income, Tax Rate * Action: calculates tax based on given income * and tax rate * Returns: float for the tax due ***********************************************/ float CalculateTax( float fIncome, float fTaxRate ) {

… code…. } /* end function CalculateTax */

28

Good Programming Habits

• Pick a function name that strongly, completely and clearly describes what the function does or returns– E.g. verb-plus-object or description of returned value

• Make sure your actual parameters (i.e. the actual data you pass to a function) matches the data type the function expects

• Make sure if you use all the parameters in your function; if not, lose the ones you don’t

• Document any assumptions about your parameters!

29

More Good Programming Habits

• Limit the number of a function’s parameters to approximately seven– Studies have shown that people can’t keep track of more

than seven pieces of info at once– (e.g. 7 digit phone numbers for a reason)

• Don’t use input parameters as working variables– i.e. don’t modify them directly– instead declare another

variable in the function, set it equal to the value of the input and use the new variable instead

• If function is to return a value, make sure it returns something under all possible circumstances


Recommended