c++ functions

Functions are the basic building blocks for C++ programs.

See chapter 7, C++ Primer Plus

.. why functions? / predefined functions

Functions ========= - like building blocks - together form larger program - divide complicated programs into manageable pieces: perfect and test - different people work on different functions simultaneously - reuse (like lego) Execution of program always begins at first statement in int main() Other functions executed ONLY when called.
    Predefined Functions ==================== Written and provided for you in libraries. Before you use it, know what it does. To use you need FOUR things: 1. library where function is defined 2. name of function 3. "type" of the function - what it returns 4. parameters the function expects: number / type / order
Example ======= Math functions in cmath library #include <cmath> double x; // Let the functions do the hard work x = pow( 2, 3 ); x = sqrt( 4 ); x = floor( 48.79 ); more about cmath here
Example ======= Time functions in ctime library #include <ctime> clock_t start, stop, cpu; // identical to int // calculate CPU time used in milliseconds ( system dependent ) start = clock( ); // gives CPU time used (including system) ... code stop = clock( ); // calculate gross time used in seconds start = time( 0 ); // gives wall clock time used (including everything) ... ... LOTS of code ... stop = time( 0 ); more about ctime here

.. user-defined functions

User defined functions ====================== YOU write these To write functions you need to: - create a well-defined purpose for the function - create function prototype ("how to" call includes params and return) - create the function definition - the code that does the work
To call these functions you need: - name of the function - number and type of parameters - return value (type) - access to the code (in your code file? another file? library?)
Code organization - ? - function prototype must be placed BEFORE function main - WHY? - where will actual function code be? - initially function definition placed AFTER end of main() - eventually - EACH function in SEPARATE file
Two function categories - void functions: do not have a data type - value-returning functions: have a data type

.. void functions

void function does not have a data type ======================================= return statement without any value used to exit the function call to a void function is a stand-alone statement prototype syntax: void functionName(); --------- definition syntax: void functionName() ---------- { statement 1; statement 2; statement 3; return; } call syntax: functionName( ); ----

void, no parameters (all code in one file) =================== #include <iostream> void hello( ); // prototype int main() { hello( ); // call return 0; } void hello( ) // definition { std::cout << "hello\n"; return; }
#include <iostream> void printStars( ); int main( ) { printStars( ); printStars( ); printStars( ); return 0; } // prints a row of 10 stars and a line return void printStars( ) { std::cout << "*********\n"; return; }

void, with parameter (all code in one file) ==================== #include <iostream> #include <string> using namespace std; void hello( string ); void printStars( ); int main( ) { // stars, names, stars printStars( ); hello( "John" ); printStars( ); return 0; } // say hello to person specified void hello( string name ) // definition { cout << "hello " << name << endl; return; } // prints a row of 10 stars and a line return void printStars( ) { cout << "*********\n"; return; }

void, with parameter (all code in one file) ==================== #include <iostream> #include <string> using namespace std; void printChars( char ); void hello( string ); int main() { // name, chars hello( "Erika" ); printChars( 'P' ); return 0; } // say hello to person specified tabbed in 1 tab void hello( string name ) // definition { cout << "\thello " << name << '\n'; return; } // print character 20 times, separated with a space and a line return void printChars( char ch ) { int rep; for ( rep = 1; rep <= 20; rep++ ) cout << ch << ' '; cout << '\n'; return; }

void, many parameters (all code in one file) ==================== #include <iostream> using namespace std; void printChars(char, int); int main() { char c; // arguments are literal constants printChars( 'x', 50 ); // argument is a variable c = 'O'; printChars( c, 20 ); // user inputs arguments cin >> c; cin >> num; printChars( c, num ); return 0; } // print n chars as specified and a line return void printChars( char ch, int n ) { int rep; for ( rep = 1; rep <= n; rep++ ) cout << ch << ' '; cout << '\n'; return; }

.. value returning Functions

value returning functions ========================= When we call a value-returning function, we can: 1. Save the value for further calculation x = sqrt( area ); 2. Use the value in some calculation z = y + sqrt( area ); 3. Print the value cout << sqrt( area ) << endl;
prototype syntax: int functionName(); --------- definition syntax: int functionName() ---------- { int x; statement 1; statement 2; return x; } call syntax: int y = functionName( ); ----

value returning, no parameters (all code in one file) ============================== #include <iostream> using namespace std; int randomOneTen( ); // prototype int main() { int num; num = randomOneTen( ); // call cout << num; // outputs number 1 to 10 return 0; } // returns random num 1-10 int randomOneTen() // definition { int ans; // always same number - what is WRONG here? ans = rand()%10; // 0-9 ans++; // make it 1-10 return ans; }

value returning, one parameter (all code in one file) ============================== #include <iostream> using namespace std; int doubsq( int ); // prototype int main( ) { int num = 3; cout << num; // outputs 3 num = doubsq( num ); // call cout << num; // outputs 36 } // doubles, then square int doubsq( int val ) // definition { int ans; ans = val * 2; ans = ans * ans; return ans; }

value returning, one parameter (all code in one file) ============================== #include <iostream> using namespace std; double compute( int ); int main() { double result; int count; // multiple calls - arg is what each call? for ( count = 1; count <= 50; count++ ) { result = compute( count ); cout << result << endl; } return 0; } // compute something fancy double compute( int num ) { double y = 0; // init needed? bad? // what happens first? y = sqrt( num ) * 3.14 + 109; y = 1 / num + y; // potential problem(s) here? return y; }

value returning, 5 parameter (all code in one file) ============================= #include <iostream> using namespace std; int compute5( int, int, int, int, int ); int main() { double result; int x, y; cin >> x >> y; //user knows what to do?? //can we do this? for (int count = 50; count > 0; count--) { result = compute5( count, count+1, x, y, 33 ); cout << result << endl; } return 0; } // compute something fancy int compute5 (int num1, int num2, int num3, int num4, int num5) { static int x = 1; // x is STATIC - WHY? OK? double y = 0; // init needed? // report calls cout << "\nFunction called " << x++ << " times.\n"; // compute y += sqrt( num1 ) * 3.14 + num4; if ( num1 != 0 )// good idea? problem? y = 1.0 / num1 + num2 * num3;// num1 always >0? other calls? return y * num5; }

.. parameters and arguments

PARAMETER ========= - variable defined by a function to be used by that function - corresponds to an argument supplied by the caller ARGUMENT ======== - the actual value passed into a function by the caller of the function - correspoinds to a parameter as defined in the function

Parameters and arguments MUST agree in: 1. type 2. number 3. position (if more than one ) not name

if funcA calls funcB each argument must agree with the corresponding parameter - type must be the same - NOT name!! funcA( argument list ) calls funcB( parameter list ) | | ------->-------->------->------- type, number, order
Normally, when a function is called, a COPY of the argument is made in the called function. Called "pass by value". Call ==== funcA (arg1, arg2); | | Function copy | | copy ======== | --------| V V void funcA (int param1, int param2) { param1 = 0; param2 = 999; return; } If the function CHANGES any of the passed values: NO effect on the original arguments in the calling function.
EXAMPLE: pass by value ======== // prototype: void, 1 parameter void hello( string ); int main() { string who = "Susie"; hello( who ); // copy of 'who' ('name') changed IN hello function cout << who; // 'who' NOT changed in main return 0; } // function definition void hello( string name ) { ^^^^ name = name + "Q" // 'name' IS changed - in function ONLY cout << "hello " << name << endl; } ----------------------------- OUTPUT: hello SusieQ // changed Susie // NOT changed -----------------------------
EXAMPLE: pass by VALUE ======== // value-returning, 1 parameter // definition int doubsq( int val ) { ^^^ val = val * 2; val = val * val; return val; } CALL ( in main() ) ---- num = 3; x = doubsq( num ); // call num copied to val ^^^ cout << x; // output will be ? cout << num; // output will be ?



.. code: triangle of stars: void function w/ value params

//Triangle of Stars, void function with parameters //Program: Print a triangle of stars /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <iostream> using namespace std; void printStars( int blanks, int starsInLine ); int main(void) { int noOfLines; // num of lines in tree int counter; // loop control int noOfBlanks; // number of blanks in line // get number of star lines & error check cout << "Enter number of star lines (1 to 20) " << "to print: "; cin >> noOfLines; while ( noOfLines < 0 || noOfLines > 20 ) { cout << "Number of star lines should be " << "between 1 and 20\n"; cout << "Enter number of star lines " << "(1 to 20) to be printed: "; cin >> noOfLines; } cout << "\n\n"; // used to make star by reducing number of blanks each star line noOfBlanks = 30; // call function noOfLines times to make tree for ( counter=1; counter <= noOfLines; counter++ ) { printStars( noOfBlanks, counter ); // 30,1 - 29,2 - 28,3 - etc... noOfBlanks--; } return 0; } //----------------------------------------------------- // prints stars with leading spaces according to params //----------------------------------------------------- void printStars( int blanks, int starsInLine ) { int count; // blanks, then stars - on same line - NO endl for ( count = 1; count <= blanks; count++ ) cout << ' '; for ( count=1; count<=starsInLine; count++ ) cout << " *"; // now end line cout << endl; return; }

.. code: value return

//Program: Static and automatic variables #include <iostream> using namespace std; int test( int ); int main() { int count, num, total=0; // can we loop like this? for ( count = 100; count < 150; count+=5 ) { num = test( count ); total += num; } cout << total << endl; return 0; } // counts and returns times called int test( int val ) { static int times = 0; // x is STATIC - WHY? val *= 2; cout << "Inside test val = " << val << " and function called " << ++times << " times." << endl; return times; }

.. c++ chapter 2, code examples 5-6


.. c++ chapter 7, code examples 1-4


.. code: counting evens odds & zeroes

// // This program generates random numbers // and counts the number of zeros, odd, and even numbers entered // ////////////////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include <ctime> using namespace std; const int N = 1000000; // where would this go in separate compilation? void zero( int&, int&, int& ); void getNumber( int& num ); // overload int getNumber( void ); // overload void classifyNumber( int num, int& zeroCount, int& oddCount, int& evenCount ); void printResults( int zeroCount, int oddCount, int evenCount ); int main ( void ) { int counter; // loop control variable int number; // new number int zeros; // number of zeros int odds; // number of odds int evens; // number of evens // init randoms srand( time(0) ); //----------------------------------------------------- // get random numbers and classify zero( zeros, odds, evens ); for ( counter = 1; counter <= N; counter++ ) { getNumber( number ); //**** classifyNumber( number, zeros, odds, evens ); } cout << endl; printResults( zeros, odds, evens ); //----------------------------------------------------- // do again only use getNumber differently // ^^^^^^^^^^^^^ zero( zeros, odds, evens ); for ( counter = 1; counter <= N; counter++ ) { number = getNumber( ); classifyNumber( number, zeros, odds, evens ); } cout << endl; printResults( zeros, odds, evens ); return 0; }
void zero( int& x, int& y, int& z ) // set 'em to ZERO { x = y = z = 0; return; }
void getNumber( int& num ) // uses a reference parameter to pass back the value { num = rand(); return; }
int getNumber( void ) // uses a return value { int num; num = rand(); return num; }
void classifyNumber( int num, int& zeroCount, int& oddCount, int& evenCount ) { // count whether number is even or odd // if even, see if zero... switch (num % 2) { case 0: evenCount++; if (num == 0) zeroCount++; break; case 1: case -1: oddCount++; } return; }
void printResults( int zeroCount, int oddCount, int evenCount ) { // simply print the calculated results cout << "There are " << evenCount << " evens, " << "which also includes " << zeroCount << " zeros" << endl; cout << "The number of odd numbers is: " << oddCount << endl; return; }
Sample Output: ----------------------------------------------------- There are 499941 evens, which also includes 47 zeros The number of odd numbers is: 500059 There are 499923 evens, which also includes 24 zeros The number of odd numbers is: 500077 -----------------------------------------------------