24
CSCI 171 Presentation 6 Functions and Variable Scope

CSCI 171 Presentation 6 Functions and Variable Scope

Embed Size (px)

Citation preview

Page 1: CSCI 171 Presentation 6 Functions and Variable Scope

CSCI 171

Presentation 6

Functions and Variable Scope

Page 2: CSCI 171 Presentation 6 Functions and Variable Scope

Functions

• Functions:– are named uniquely– perform specific tasks– are independent

• should not interfere with other parts of program

– may need data to accomplish their task• parameters (arguments)

– may send data back to their initiator• returning a value

Page 3: CSCI 171 Presentation 6 Functions and Variable Scope

Function Example #include <stdio.h>

double calcForce (double, double); //function prototype

int main( void ) { double mass = 3; double acceleration = 4; double force = 0; force = calcForce (mass, acceleration); //calling the function printf("%lf", force); }

double calcForce(double m, double a) //function header {

return (m * a); //function body }

Page 4: CSCI 171 Presentation 6 Functions and Variable Scope

Function Example - cont’d

• Function definition (header and body):

double calcForce(double m, double a) {

return (m * a); }

• Function name is: calcForce• Function parameters are: 2 doubles (m and a)• Function returns: 1 double

Page 5: CSCI 171 Presentation 6 Functions and Variable Scope

Sample Program 7.1#include <stdio.h>

float findArea(float, float);

void main() {float base = 0, height = 0, area = 0;

printf("Enter triangle base: ");scanf("%f", &base);printf("Enter triangle height: ");scanf("%f", &height);area = findArea(base, height);printf("The area is: %.2f", area);

}

float findArea(float b, float h) {float area = 0;area = 0.5 * b * h;return area;

}

Page 6: CSCI 171 Presentation 6 Functions and Variable Scope

How a function works

• Is not executed unless called

• “Calling function” sends in any arguments– information to perform the process

• Control returns to – statement following function call (if no return)– function call (if a value is returned)

Page 7: CSCI 171 Presentation 6 Functions and Variable Scope

Parts of a function

• Prototype– function name– argument type(s)– return type

• Definition– header– body (actual code)

Page 8: CSCI 171 Presentation 6 Functions and Variable Scope

Local Variables

• Variables declared within a function are local– only defined within the function– not accessible by other functions

• Arguments act locally as well

Page 9: CSCI 171 Presentation 6 Functions and Variable Scope

Note the local variables in 7.1#include <stdio.h>

float findArea(float, float);

void main() {float base = 0, height = 0, area = 0;

printf("Enter triangle base: ");scanf("%f", &base);printf("Enter triangle height: ");scanf("%f", &height);area = findArea(base, height);printf("The area is: %.2f", area);

}

float findArea(float b, float h) {float area = 0;area = 0.5 * b * h;return area;

}

Page 10: CSCI 171 Presentation 6 Functions and Variable Scope

Return values

• Functions may have more than 1 return value, but only 1 is ever returned– Generally this is bad structure, not suggested

• Ex: if (a > b) return a; else return b;

Page 11: CSCI 171 Presentation 6 Functions and Variable Scope

Return types

• Return type is declared in function header & prototype• Actual value being returned is in return statement• Examples:

double calcForce(double m, double a) {

return (m * a); }

float findArea(float b, float h) {float area = 0;area = 0.5 * b * h;return area;

}

Page 12: CSCI 171 Presentation 6 Functions and Variable Scope

No return type

• void specifies that there is no return value

• no return statement in function

• Ex: void writeErrorMessage() { printf(“\nInvalid input”); printf(“\nPlease check specifications”); errorCount += 1; }

Page 13: CSCI 171 Presentation 6 Functions and Variable Scope

Calling a function

• Calling a function with no returnwriteToFile( );

• Calling a function with a return valuex = square(3);printf(“The square of 3 is: %d”, square(3));

• Calling a function as a parameter c = sumTheValues(square(3), square(4));

• Multiple functions in an expressionb = square(3) + square(4);

Page 14: CSCI 171 Presentation 6 Functions and Variable Scope

Global Variables

• Placed outside of all functions

• Scope of variable is entire program– can be accessed by any function within the file

• Generally considered bad programming style

Page 15: CSCI 171 Presentation 6 Functions and Variable Scope

Sample Program 7.6

#include <stdio.h>

double force = 0.0; //Global variable – accessible to all functions in file

double calcForce (double, double);

int main( void ) {double mass = 3.0;double acceleration = 4.0;

force = calcForce (mass, acceleration);printf("%lf", force);

}

void calcForce(double m, double a) //function header {

force = m * a;}

Page 16: CSCI 171 Presentation 6 Functions and Variable Scope

What is scope?

• Parts of program which can access a variable– accessibility– visibility

• How long variable takes up system resources (memory)– Dynamic memory allocation

Page 17: CSCI 171 Presentation 6 Functions and Variable Scope

Scope

Program 1 (compiles) | Program 2 (does not compile)int x = 999; | void squareX()

|

void squareX(); | void main() {

| int x = 999;

void main() { | x = x * x;

x = x * x; | }

} |

| void squareX() {

void squareX () { | x = x * x;

x = x * x; | }

} |

Page 18: CSCI 171 Presentation 6 Functions and Variable Scope

Importance of scope

• Modularization– each function should be independent– variables isolated from interference

• Scope allows for control over degree of isolation

Page 19: CSCI 171 Presentation 6 Functions and Variable Scope

Local Variables

• Defined within a code block

• Visibility limited to that code block

• Usually a function’s local variable’s value is re-initialized with each call to the function

• Can request variable not be destroyed– static keyword

Page 20: CSCI 171 Presentation 6 Functions and Variable Scope

Local variables - example

void main() {

outputNumbers();

outputNumbers();

outputNumbers();

}

____________________________

void outputNumbers() { | Program output:

static int x = 0; | 0 0

int y = 0; | 1 0

printf(“\n%d %d”, x++, y++); | 2 0

} |

Page 21: CSCI 171 Presentation 6 Functions and Variable Scope

Parameters and Scope

• A variable in the parameter list acts locally

void function1(int x) {

int y = 0;

printf(“%d %d”, x, y);

}

• In the preceding:– x is a parameter (and so is only accessible within the function)

– y is a local variable (and so is only accessible within the function)

Page 22: CSCI 171 Presentation 6 Functions and Variable Scope

Register variables

• Suggests that a local variable be stored in processor register (not regular memory)

void function1() {

register int x;

….

}

• Any processing with x will be done quicker• Can only be used with simple numeric variables

– can’t use with arrays, structures, etc.

Page 23: CSCI 171 Presentation 6 Functions and Variable Scope

Code Blocks

• Variables can be declared as local within program blocks (statements enclosed in {})

void main() { int count = 0; printf(“%d”, count); { int count = 10; printf(“%d”, count); } printf(“%d”, count); }

Page 24: CSCI 171 Presentation 6 Functions and Variable Scope

Guidelines

• Initialize all variables• Pass data as function parameters unless

most functions use the data• Use symbolic constants for constant data

that is used in most of the functions– PI in a math library

• Put definitions at beginning of scope– functions, files, etc.