C++ Functions and Structs
In this lecture, we will learn
◼ User-Defined Functions
◼ User-Defined Simple Data Types
Predefined Functions
◼ Some of the predefined mathematical functions are:
cin/cout
sqrt(x)//square root function
pow(x, y)//power function
floor(x) //returns the largest integer is not greater than x
◼ Predefined functions are organized into separate libraries
◼ I/O functions are in iostream header
◼ Math functions are in cmath header
#include <iostream> #include <cmath>
Notes
◼ To use these functions, you must:
◼ Include the appropriate header file in your program using the include
statement
◼ Know the following items:
◼ Name of the function
◼ Number and data type of parameters, if any
◼ Data type of the value returned, if any
#include <iostream> #include <cmath> #include <cstdlib> //abs double x = 9.0, y = 48.79, z; int m=-7,n; z = sqrt(x); z = floor(y); n = abs(m);
User-Defined Functions
◼ Value-returning functions: have a return type
◼ Return a value of a specific data type using the return statement
◼ Void functions: do not have a return type
◼ Do not use a return statement to return a value
◼ You can use return statement to exit the function
Syntax: Value-Returning Function
◼ Syntax:
◼ functionType is also called the data type or return type
◼ Syntax: Formal Parameter List
double larger(double x, double y) {
double max;
if (x >= y) max = x;
else max = y;
return max; }
◼ Syntax to call a value-returning function:
◼ Syntax of the actual parameter list:
double num1 = 13.00; double num2 = 36.53; double maxNum;
maxNum=larger(5, 6); maxNum=larger(nym1, num2); maxNum=larger(num1, 29); cout<<larger(38.46,56.78);
◼ Consider the following statements (Assume that all
variables are properly declared.)):
int x,y,one=1,two=2;
x = larger(int one, 29); y = larger(int one, int 29);
cout << larger(int one, int two);
◼ Function returns its value via the return statement
◼ It passes this value outside the function
◼ Syntax:
◼ Function immediately terminates
◼ Control goes back to the caller
double compareThree(double x, double y, double z) {
return larger(x, larger(y, z)); }
//function call compareThree(10, 20, 30);
◼ Formal parameter list can be empty (e.g., Formal parameters are optional):
◼ A call to a value-returning function with an empty formal parameter list is:
int getRandomNum() { int num; srand(time(0)); num=rand()%100+1; return num;
}
// function call cout<<getRandomNum();
Final Program
◼ larger
◼ compareThree
◼ main
Program: http://codepad.org/SYQj014o
Function Prototype
◼ Function prototype:
◼ function heading without the body of the function
◼ Syntax:
◼ Data type of each parameter must be specified
◼ Not necessary to specify the variable names in the parameter list
double larger(double x, double y); //function prototype double larger(double, double); //function prototype
Flow of Execution
◼ Execution always begins at the first statement in the function main
◼ Other functions are executed only when called
◼ User-defined void functions can be placed either before or after the
function main
◼ Function prototypes appear before any function definition
◼ Compiler translates these first
◼ Compiler can then correctly translate a function call
◼ Function call transfers control to the first statement in the body of the
called function
◼ When the end of a called function is executed,
◼ control is passed back to the point immediately following the function call
◼ Function’s returned value replaces the function call statement
Value-Returning Functions: Some Peculiarities
Question?
int secret(int x) {
if (x > 5) //Line 1 return 2 * x; //Line 2
}
Correction
Right !
Void Functions
◼ If user-defined void functions are placed after the function main
◼ The function prototype must be placed before the function main
◼ Void function does not have a return type
◼ return statement without any value is typically used to exit the
function early
◼ syntax:
◼ Syntax: Formal Parameter List
void printGrade(int cScore) {
cout << "Your grade for the course is ";
if (cScore >= 90) //Line 8 cout << "A." << endl;
else if (cScore >= 80) cout << "B." << endl;
else if(cScore >= 70) cout << "C." << endl;
else if (cScore >= 60) cout << "D." << endl;
else cout << "F." << endl;
}
// function call
printGrade(50);
Value-Returning Function Void Functions
functionType functionName(formal parameter list)
{
statements
}
void functionName(formal parameter list)
{
statements
}
functionType functionName(parameter list); void functionName(parameter list);
variable = functionName(actual parameter list); functionName(actual parameter list);
Definition
Prototype
Call
Problem 1:
◼ We write a program to print a pattern (a triangle of stars)
similar to the following:
◼ define a function printStars that has two parameters,
◼ a parameter to specify the number of blanks before the stars in a line
◼ a second parameter to specify the number of stars in a line.
Functions ◼ Value parameter:
◼ a formal parameter that receives a copy of the content of corresponding actual
parameter
◼ Arguments passed by value
◼ Reference parameter:
◼ a formal parameter that receives the location (memory address) of the
corresponding actual parameter
◼ Arguments passed by reference
◼ Pointer parameter:
◼ Arguments passed by pointer
void printGrade(int cScore)
void swap(int& x, int& y);
void swap(int* x, int* y);
Value Parameters
◼ If a formal parameter is a value parameter:
◼ The value of the corresponding actual parameter is copied into
formal parameter
◼ Formal parameter has its own copy of the data
◼ During program execution
◼ Formal parameter manipulates the data stored in its own
memory space
Example #include <iostream> using namespace std;
void swap(int x, int y);
int main () { // local variable declaration: int a = 100;int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0;
}
void swap(int x, int y) { int temp; temp = x; x = y;y = temp; return;
} http://codepad.org/8PzUtxLr
Reference Variables as Parameters
◼ If a formal parameter is a reference parameter
◼ It receives the memory address of the corresponding actual
parameter
◼ During program execution to manipulate data
◼ Changes to formal parameter will change the corresponding
actual parameter
#include <iostream> using namespace std;
void swap(int& x, int& y);
int main () { // local variable declaration: int a = 100;int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0;
}
void swap(int& x, int& y) { int temp; temp = x; x = y;y = temp; return;
} http://codepad.org/frX4IpHw
◼ Reference parameters are useful in three situations:
◼ Changing the actual parameter
◼ When passing the address would save memory space and time
◼ Returning more than one value
Review
void printGrade(int cScore) {
cout << "Your grade for the course is ";
if (cScore >= 90) //Line 8 cout << "A." << endl;
else if (cScore >= 80) cout << "B." << endl;
else if(cScore >= 70) cout << "C." << endl;
else if (cScore >= 60) cout << "D." << endl;
else cout << "F." << endl;
}
// function call
printGrade(50);
Problem 2: Calculate Grade
◼ Write a program to take a course score (a value between 0
and 100) and determine a student’s course grade.
◼ Three functions:
◼ main
◼ Get the course score.
◼ Print the course grade.
◼ getScore
◼ Prompt the user for the input.
◼ Get the input.
◼ Print the course score.
◼ printGrade
◼ Calculate the course grade.
◼ Print the course grade.
#include <iostream> using namespace std;
void getScore(int& score);
void printGrade(int score);
int main() {
int courseScore; cout << "Based on the course score, \n" << " this program computes the " << "course grade." << endl; getScore(courseScore); printGrade(courseScore); return 0;
}
void getScore(int& score) {
cout << "Line 4: Enter course score: "; cin >> score; cout << endl << "Course score is "<< score << endl;
}
http://codepad.org/KxvihqRl
Reference Variables
◼ Safer version of C/C++ pointer
◼ “Refer to” a variable
◼ Effectively an alias for the variable to which it refers
◼ Another name for an existing variable
◼ Used exactly like the variable to which it refers (No ‘*’)
◼ Using ‘&’ after datatype in the declaration makes it a reference (but do
not read it as ‘address of’)
◼ Must be initialized during declaration
◼ It can be initialized with already declared variables only.
◼ Reference variables can not be updated.
int a=10; int& nicka=a; // or int &nicka=a;
◼ What is the output of the program?
#include <iostream> using namespace std;
int main(){ double x=10;
double& nickx=x;
nickx++;
cout<<nickx << " "<<x; }
◼ What is the output of the program?
#include <iostream> using namespace std;
int main(){ double x=10;
double& nickx=x;
nickx++;
cout<<nickx << " "<<x; }
double y=20; nickx=y; // illegal
10
x
nickx
20
y
◼ a
getScore(courseScore); // in main function
void getScore(int& score) {
cout << "Line 4: Enter course score: "; cin >> score; cout << endl << "Course score is "<< score << endl;
}
80
courseScore score
swap(a, b);// in main function
void swap(int& x, int& y) { int temp; temp = x; x = y;y = temp; return;
}
100 200
a x b y
Reference Variables as Parameters
◼ Another Example: void change(int &a);
void main() {
int x = 2; change(x); cout << x << endl; return;
}
void change(int &a) {
a = a + 10; }
◼ Pass-by-Value
◼ When a function is called
◼ Memory for its formal parameters
and its local variables is allocated in
the function data area
◼ For a value parameter, the actual
parameter’s value is copied into the
formal parameter’s memory cell
◼ Changes to the formal parameter
do not affect the actual
parameter’s value
◼ Pass-by-Reference
◼ For a reference parameter, the actual
parameter’s address passes to the
formal parameter
◼ Both formal and actual parameters
refer to the same memory location
◼ During execution, changes made to
the formal parameter’s value
permanently change the actual
parameter’s value
Value VS Reference
◼ What is the output of the program? void change1(int &a); void change2(int a);
void main(){ int x = 2, y = 2; change1(x); change2(y); cout << x << ' ' << y << endl; return;
}
void change1(int &a){ a = a + 10;
}
void change2(int a){ a = a + 10;
}
Arrays as Parameters to Functions
◼ Arrays are passed by reference only
◼ Do not use symbol ‘&’ when declaring an array as a formal
parameter
◼ Size of the array is usually omitted
◼ If provided, it is ignored by the compiler
◼ Solution: use another parameter to represent the size
◼ Example:
◼ Base address of an array: address (memory location) of
the first array component
◼ Example:
◼ If list is a one-dimensional array, its base address is the address
of list[0]
◼ When an array is passed as a parameter, the base address
of the actual array is passed to the formal parameter
Functions Cannot Return a Value of the Type Array
◼ C++ does not allow functions to return a value of type
array
◼ Solution:
◼ Use void function and pass array as the parameter
Initialize(list,10); // function call
Example
initialize(list,10); // function call printArray(list,10);
Constant Arrays as Formal Parameters
◼ Can prevent a function from changing the actual parameter
when passed by reference
◼ Use const in the declaration of the formal parameter
◼ Example:
Passing Two-Dimensional Arrays as Parameters to Functions
◼ Two-dimensional arrays are passed by reference as
parameters to a function
◼ Base address is passed to formal parameter
◼ Two-dimensional arrays are stored in row order
◼ When declaring a two-dimensional array as a formal
parameter, can omit size of first dimension, but not the
second
C
i
g
n
,
S
e
v
e
n
t
h
E
d
i
t
i
o
n
4
8
◼ Prototype
◼ Definition
◼ Definition
Reference Parameters and Value-Returning Functions
◼ Can also use reference parameters in a value-returning
function
◼ Not recommended
◼ By definition, a value-returning function returns a single
value via return statement
◼ If a function needs to return more than one value,
◼ change it to a void function and use reference parameters to
return the values
◼ Question:
Are you allowed to access any
identifier anywhere in the program?
Scope of an Identifier
◼ Scope of an identifier:
◼ where in the program the identifier is accessible
◼ Local identifier: identifiers declared within a function (or block)
◼ Global identifier: identifiers declared outside of every function
definition
◼ C++ does not allow nested functions
◼ Definition of one function cannot be included in the body of another
function
◼ Rules when an identifier is accessed:
◼ Global identifiers are accessible by a function or block if:
◼ Declared before function definition
◼ Function name different from identifier
◼ Parameters to the function have different names
◼ All local identifiers have different names
// global scope int a; int main() { a = 2;
}
//block scope int main() { {
int x = 10; } {
cout<<x; } return 0;
}
// function scope int a; int main() { a = 2;
}
void swap(int& x, int& y) { int temp;
}
// file scope int a; static int b; int main() { a = 2;
}
http://www.ccplusplus.com/2011/08/scope-of-identifiers-in-c.html
Static and Automatic Variables
◼ Automatic variable: memory is allocated at block entry
and deallocated at block exit
◼ By default, variables declared within a block are automatic
variables
◼ Static variable: memory remains allocated as long as the
program executes
◼ Global variables declared outside of any block are static variables
◼ Can declare a static variable within a block by using the
reserved word static
◼ Syntax:
◼ Static variables declared within a block are local to the
block
◼ Have same scope as any other local identifier in that block
◼ What is the output of the following program?
int main() {
int count; for (count = 1; count <= 5; count++)
test(); return 0;
}
void test() {
static int x = 0; int y = 10; x = x + 2; y = y + 1; cout << "Inside test x = " << x << " and y = "<< y << endl;
}
Function Overloading: An Introduction
◼ In a C++ program, several functions can have the same
name
◼ Function overloading: creating several functions with the
same name
◼ Function signature: the name and formal parameter list of
the function
◼ Does not include the return type of the function
Function Overloading (cont’d.)
◼ Two functions are said to have different formal parameter
lists if both functions have either:
◼ A different number of formal parameters
◼ If the number of formal parameters is the same, but the data type
of the formal parameters differs in at least one position
◼ Overloaded functions must have different function
signatures
◼ The following functions all have different formal parameter lists:
◼ The following functions have the same formal parameter list:
void functionOne(int x) void functionTwo(int x, double y) void functionThree(double y, int x) int functionFour(char ch, int x, double y) int functionFive(char ch, int x, string name)
void functionSix(int x, double y, char ch) void functionSeven(int one, double u, char firstCh)
◼ Correct function overloading:
◼ Syntax error:
void functionXYZ() void functionXYZ(int x, double y) void functionXYZ(double one, int y) void functionXYZ(int x, double y, char ch)
void functionABC(int x, double y) int functionABC(int x, double y)
Functions with Default Parameters
◼ In a function call,
◼ the number of actual and formal parameters must be the same
◼ C++ relaxes this condition for functions with default parameters
◼ Can specify the value of a default parameter in the
function prototype
◼ If you do not specify the value for a default parameter
when calling the function, the default value is used
◼ All default parameters must be the rightmost parameters
of the function
◼ If a default parameter value is not specified:
◼ You must omit all of the arguments to its right
◼ Default values can be constants, global variables, or
function calls
◼ Cannot assign a constant value as a default value to a
reference parameter
◼ Consider the following prototype:
◼ Assume:
◼ a, b are int, ch is char, d is double
◼ Examples of illegal calls:
void funcExp(int t, int u, double v, char w = 'A', int x = 67,char y = 'G’, double z = 78.34);
funcExp(a, b, d); funcExp(a, 15, 34.6, 'B', 87, ch); funcExp(b, a, 14.56, 'D');
funcExp(a, 15, 34.6, 46.7); funcExp(b, 25, 48.76, 'D', 4567, 78.34);
◼ Look at function prototypes with default parameters:
◼ More examples
void funcExp(int t, int u, double v, char w = 'A', int x = 67,char y = 'G’, double z = 78.34);
void funcOne ( int x, double z = 23.45, char ch, int u = 45);
int funcTwo ( int length = 1, int width, int height = 1);
void funcThree ( int x, int& y = 16, double z = 34);
Summary
◼ Function
◼ Parameters
◼ Value parameter
◼ Reference parameter
◼ Default parameter
◼ Scope of an Identifier
◼ Variables
◼ Automatic variable
◼ Static variable