+ All Categories
Home > Documents > UCLA CS 31 Lecture 6 Post

UCLA CS 31 Lecture 6 Post

Date post: 01-Oct-2015
Category:
Upload: manuel-sosaeta
View: 14 times
Download: 0 times
Share this document with a friend
Description:
UCLA CS 31 Lecture 6 Post
Popular Tags:
32
Monday, October 25 th Function Review More on Functions Passing Variables using “References” Function Overloading and Default Parameters Global and Static Variables Detecting errors in functions
Transcript
  • Monday, October 25th Function ReviewMore on FunctionsPassing Variables using ReferencesFunction Overloading and Default Parameters Global and Static VariablesDetecting errors in functions

  • Function Reviewint square(int x); // int square(int);

    int main(void){int n;cout > n;cout

  • Function Reviewint square(int x);// prototype

    int main(void){int n;cout > n;cout

  • Function Reviewstring nickname(int x);// prototype

    int main(void){int age;cout > age;cout

  • Function Reviewvoid eat(int x);// prototype

    int main(void){int prunes;cout

  • // prototype:void barf(void);int main(void){int n = 10;barf();cout
  • // prototype:void barf(void);int main(void){int n = 10;barf();cout
  • // prototype:void barf(void);int main(void){int x = 10;barf();barf();}// definitionvoid barf(void){int n; // localcout
  • Function Challenge#1. Write a function called charfind that:

    Accepts a string parameter and a char parameterReturns the index in the string of the first occurrence of the character.If the char cant be found, your function should return -1.void main(void){ int n;

    n = charfind(hello, l); cout

  • Functions: Understanding Parameters Questions:What does this program print?Does the value of n change?Why or why not?void change_me(int x);int main(void){ int n; cout > n; cout
  • Functions: Understanding Parameters void change_me(int x);int main(void){ int n; cout > n; cout
  • Functions and Reference Parameters

    void swap(int a, int b){int temp;temp = a;a = b;b = temp;}void main(void){int x = 10, y = 20;swap( x, y); cout

  • Functions and Reference Parameters The previous program was supposed to swap mains x and y variables. So how can we let one function modify another functions variables?Answer: Using references!It didnt work because the swap function swaps its own local variables and not mains variables.

  • Functions and Reference Parameters

    void swap(int a, int b){int temp;temp = a;a = b;b = temp;}void main(void){int x = 10, y = 20;swap( x, y); cout

  • Reference ParametersYou can use a reference parameter to modify a variable from the calling function.Any time you access the reference parameter, youre really accessing the variable in the calling function.Syntax: Place an & between a parameters type and its name in the function header:

    void SomeFunction(int & doe, float & ray, string & mi) { etc

  • Functions and Reference Parameters

    void cheer(string &s){

    s = s + fight, ;}void main(void){ string msg = UCLA "; cheer(msg); cout

  • Reference Parameters

    void add4(float &x){ x += 4;}

    void add7(float &y){ y += 3; add4(y);}void main(void){ float a = 50.0;

    add7(a); cout

  • Functions and Reference Parameters Whats wrong with it?If youre going to pass a value to a function with a reference parameter, the types must match exactly!void zero_it( int &i ){i = 0;}void main(void){double d = 10;zero_it(d); // SYNTAX ERROR} The type of the reference parameter must match exactly with the type of the argument.

    In this case, were trying to pass a double variable to an integer parameter. BAD!

  • Functions and Default Parametersvoid fish( int eyes = 2 );void cows(int udders = 3, int hooves = 4 );void fish(int eyes){ cout
  • Functions and Default Parametersvoid flies(int eyes, int legs = 6, int ears = 9);

    void flies(int eyes, int legs, int ears){ cout

  • Functions and Default Parametersvoid flies(int eyes, int legs = 6, int ears = 9);

    void spiders( int legs=4, int eyes, int noses=1);

    void flies(int eyes, int legs, int ears){ ...}

    void spiders(int legs, int eyes, int noses){ ...}

    void main(){ spiders(5,6); // does it mean spiders(5,6,1); // or spiders(4,5,6); ???} Rule: All default parameters must be to the right of all non-default parameters for a given function.

  • Functions and Overloadingvoid area( int r ) { cout
  • Functions and Overloadingint getcircum( int rad ){ return(2 * 3 * rad); // 2*PI*rad}

    float getcircum( int rad ){ return(2 * 3.14159 * rad); }

    void main(void){ int icircum; float fcircum;

    icircum = getcirum(5); fcircum = getcirum(6);}

    It is illegal in C++ to overload a function JUST based on its return type.Overloaded functions MUST have different parameter types in their lists.// bad example

  • Variables in FunctionsAs weve seen, each function has its own local variables.A function can only access its own local variables or those variables passed by reference. (at least thats what weve learned so far)Now, lets learn about two new types of variables: global variables and static variables.

  • Global VariablesIf you want a variable to be accessible and modifiable from ALL functions, you can use a global variable. int gN;// gN is global. void change_me(void);void main(void){cout > gN;cout
  • Global Variables#include

    string msg = Carey;

    void talk(string word){ msg = msg + + word;}

    int main(void){ talk(is); talk(silly!);

    cout

  • Static VariablesFunctions can have variables whose values dont disappear every time the function exits. These are called static variables.The static variable is initialized once and only once the first time the function is called.If you do not explicitly initialize a static variable, it starts out with a value of 0.Static variables, like local variables, are only visible in the function where they are defined.void ucla(void);void main(void){ucla();ucla();ucla();}void ucla(void){static int a = 10;cout
  • Static VariablesIf you do not explicitly initialize a static variable, it starts out with a value of 0 the first time the function runs.void sum(int val);void main(void){ sum(3); sum(6);}void sum(int val){ static int total;

    total += val; cout

  • Globals, Statics and Local Variables int careful = -10; // global!void hmm(void) { int careful = 100; cout
  • Functions: Dealing with ERRORS!What should you do if one of your functions has an error while it runs?float Cosine(float op, float adj, float hypotenuse ){ float result;

    return(result);}

    int main(void){ cout

  • Functions: Dealing with ERRORS!So how would we rewrite our function to return an error and the proper cosine value?Heres how we do itFirst, lets change the function so it returns the result by reference.

    )float Cosine(float op, float adj, float hypotenuse , float &result)if (hypotenuse != 0)Next, update the function so it returns a boolean result

    {

    return(true); // success!} false ); // failure! boolFinally, update your other functions to call the new one properly

    float c;

    if (Cosine(3,4,0,c) == true) cout

  • Functions: Dealing with ERRORS!So in summaryIf a function may encounter errors, it should return an error/success status result.All functions should check status results after calling other functions and act appropriately.If a boolean return value is not sufficient, you can consider using integer values instead


Recommended