0% found this document useful (0 votes)
10 views

Lecture7 - Function Using in Conceptual Organization of A Program

This document discusses functions in C++. It covers defining functions with declarations and definitions, calling functions, passing arguments to functions by value and by reference, returning values from functions including structures, and passing structures by reference. Functions allow grouping code and reuse, and passing arguments and returning values allows customizing a function's behavior.

Uploaded by

Pyae Linn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture7 - Function Using in Conceptual Organization of A Program

This document discusses functions in C++. It covers defining functions with declarations and definitions, calling functions, passing arguments to functions by value and by reference, returning values from functions including structures, and passing structures by reference. Functions allow grouping code and reuse, and passing arguments and returning values allows customizing a function's behavior.

Uploaded by

Pyae Linn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CST-12102

Programming in C++

Lecture 7
Function: Using in Conceptual Organization of a Program
1
Function
• groups a number of program statements into a unit and gives it a name
• can be invoked from other parts of the program

Faculty of Computer Science 2


Function Syntax
• Function Declaration
• Call to Function
• Function Definition

Faculty of Computer Science 3


Function Component

Faculty of Computer Science 4


Simple Function
// Page 163 - table.cpp
// demonstrates simple function
#include <iostream.h>
void starline(); //function declaration (prototype)
int main()
{ starline(); //call to function
cout << "Data type Range" << endl;
starline(); //call to function
cout << "char -128 to 127" << endl
<< "short -32,768 to 32,767" << endl
<<"int System dependent" << endl
<< "long -2,147,483,648 to 2,147,483,647" << endl;
starline();
return 0; //call to function
} Faculty of Computer Science 5
Cont’d
// starline()
// function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << '*'; *********************************************
cout << endl; Data type Range
*********************************************
} char -128 to 127
short -32,768 to 32,767
int System dependent
long -2,147,483,648 to 2,147,483,647
*********************************************

Remark: Eliminating Function Declarations


// Page 167 Example
6
// table2.cpp
Passing Arguments to Functions
• An argument is a piece of data (an int value, for example) passed from
a program to the function.
• Arguments allow a function to operate with different values, or even
to do different things, depending on the requirements of the program
calling it.
• Passing by Value - where the function works with a copy of the
argument
▪ Passing Constants
▪ Passing Variables
• Passing by Reference - where the function works with the original
argument in the calling program

Faculty of Computer Science 7


Passing Constants
#include<iostream.h> void repchar(char ch,int n )
void repchar(char, int); {
int main() for(int j=0;j<n;j++)
{ cout<<ch;
repchar('-',43); cout<<endl;
cout<<"Data Type Range"<<endl; }
repchar('=',23);
cout<<"char -128 to 127"<<endl
-------------------------------------------
<<"short -32768 to 32,767"<<endl
Data Type Range
<<"int System dependent"<<endl =======================
<<"long -2,147,483,648 to char -128 to 127
2,147,483,647"<<endl; short -32768 to 32,767
int System dependent
repchar('-',43); long -2,147,483,648 to
return 0; 2,147,483,647
} -------------------------------------------

Faculty of Computer Science 8


Passing Variables
#include<iostream.h>
void repchar(char,int); Passing by Value
int main()
{
char chin;
int nin;
cout<<"Enter a character:";
cin>>chin;
cout<<"Enter number of times to
repeat it:";
cin>>nin;
repchar(chin,nin);
return 0;
}
void repchar(char ch,int n )
{
for(int j=0;j<n;j++)
cout<<ch; Enter a character: a
Enter number of times to repeat it:3
cout<<endl;
aaa 9
}
Returning Values from Functions
#include<iostream.h> float lbstokg(float pounds)
float lbstokg(float); {
float kilograms=0.453592*pounds;
int main()
return kilograms;
{
}
float lbs,kgs;
cout<<"Enter your weight in
pounds:";
cin>>lbs;
kgs=lbstokg(lbs);
cout<<"Your weight in kilograms
is"<<kgs<<endl;
return 0;
} Faculty of Computer Science 10
Returning Values from Functions

Faculty of Computer Science 11


Structures as Arguments
#include<iostream.h> cout<<"Enter inches:";
struct Distance cin>>d2.inches;
{ int feet; cout<<"\nd1= ";
float inches; engldisp(d1);
}; cout<<"\nd2= ";
void engldisp(Distance); engldisp(d2);
int main() cout<<endl;
{ Distance d1,d2; return 0;
cout<<"Enter feet:"; }
cin>>d1.feet; void engldisp(Distance dd)
cout<<"Enter inches:"; {
cin>>d1.inches; cout<<dd.feet<<"\'“
cout<<"\nEnter feet:"; <<dd.inches<<"\""; 12
cin>>d2.feet;
Returning Structure Variables
#include<iostream.h> cout<<"Enter feet:";
struct Distance cin>>d2.feet;
{ int feet; cout<<"Enter inches:";
float inches; }; cin>>d2.inches;
Distance addengl(Distance,Distance); d3=addengl(d1,d2);
void engldisp(Distance); cout<<endl;
int main() engldisp(d1);
{ Distance d1,d2,d3; cout<<"+";
cout<<"Enter feet:"; engldisp(d2);
cin>>d1.feet; cout<<"=";
cout<<"Enter inches:"; engldisp(d3);
cin>>d1.inches; cout<<endl;
return 0; 13
Returning Structure Variables
Distance addengl(Distance dd1,Distance dd2)
{
Distance dd3;
dd3.inches=dd1.inches+dd2.inches;
dd3.feet=0; if(dd3.inches>=12.0)
{
dd3.inches-=12.0;
dd3.feet++;
}
dd3.feet+=dd1.feet+dd2.feet;
return dd3;
}
void engldisp(Distance dd)
{
cout<<dd.feet<<"\'-"<<dd.inches<<"\""; 14
Faculty of Computer Science
}
Passing by Reference
A reference provides an alias—a different void intfrac(float n, float& intp,
name—for a variable. float& fracp)
#include<iostream.h> {
int main() long temp=static_cast<long>(n);
{ intp=static_cast<float>(temp);
void intfrac(float,float&, float&); fracp=n-intp;
float number,intpart,fracpart;
}
do{
cout<<"\nEnter a real nmber:";
cin>>number;
intfrac(number, intpart, fracpart);
cout<<"Integer part is"<<intpart
<<", fraction part is <<fracpart<<endl;
}while(number!=0.0);
return 0;
} Faculty of Computer Science 15
Passing by Reference
#include<iostream.h> void order(int & num1,int& num2)
void order(int&,int&); {
int main() if(num1>num2)
{ {
//void order(int&,int&); int temp=num1;
int n1=99,n2=11; num1=num2;
int n3=22,n4=88; num2=temp;
order(n1,n2); }
order(n3,n4); }
cout<<"n1="<<n1<<endl;
cout<<"n2="<<n2<<endl;
cout<<"n3="<<n3<<endl;
cout<<"n4="<<n4<<endl;
return 0;
Faculty of Computer Science 16
}
Passing Structures by Reference
#include<iostream.h> cout<<"\nd1= ";
struct Distance engldisp(d1);
{ int feet; cout<<"\nd2= ";
float inches; }; engldisp(d2);
void scale(Distance&, float); cout<<endl;
void engldisp (Distance); return 0;
int main() }
{ Distance d1={12,6.5}; void scale(Distance& dd , float factor)
Distance d2={10,5.5}; {
cout<<"d1= "; float inches=(dd.feet*12+dd.inches)*factor;
engldisp(d1); dd.feet=static_cast<int>(inches/12);
cout<<"\nd2= "; dd.inches=inches-dd.feet*12;
engldisp(d2); }
scale(d1,0.5); void engldisp(Distance dd)
scale(d2,0.25); { cout<<dd.feet<<"\'-"<<dd.inches<<"\""; }
Faculty of Computer Science 17
Functions
• Functions can return only one value. Functions ordinarily return by
value, but they can also return by reference.

• An is actually a group of functions


with the same name. Which of them is executed when the function is
called depends on the type and number of arguments supplied in the
call.

involves a function calling itself

• An looks like a normal function in the source file


but inserts the function’s code directly into the calling program.
Inline functions execute faster but may require more memory than
normal functions unless they are very small. Functions that are very
short, say one or two statements, are candidates to be inlined. 18
Overloaded Function
#include<iostream.h> void repchar(char ch)
void repchar(); {
void repchar(char); for(int j=0;j<45;j++)
void repchar(char,int); cout<<ch;
int main() cout<<endl;
{ repchar(); }
repchar('='); void repchar(char ch,int n)
repchar('+',30); {
return 0; for(int j=0;j<n;j++)
} cout<<ch;
void repchar() cout<<endl;
{ for(int j=0;j<45;j++) }
cout<<'*';
cout<<endl;
Faculty of Computer Science 19
}
Different Kinds of Arguments
#include<iostream.h> cout<<"\nd1= ";
struct Distance engldisp(d1);
{ int feet; cout<<"\nd2= ";
float inches; }; engldisp(d2);
void engldisp(Distance); cout<<endl;
void engldisp(float); return 0; }
int main() void engldisp(Distance dd)
{ Distance d1; {
float d2; cout<<dd.feet<<"\'-"<<dd.inches<<"\"";
cout<<"Enter feet:"; }
cin>>d1.feet; void engldisp(float dd)
cout<<"Enter inches:"; {
cin>>d1.inches; int feet=static_cast<int>(dd/12);
cout<<"\nEnter entire distance in float inches=dd-feet*12;
inches:"; cout<<feet<<"\'-"<<inches<<"\"";
cin>>d2; Faculty of Computer
} Science 20
Recursion
#include <iostream.h> unsigned long factfunc(unsigned long n)
unsigned long factfunc(unsigned {
long); if(n > 1)
int main() return n * factfunc(n-1);
{ else
int n; return 1;
unsigned long fact; }
cout << "Enter an integer: ";
cin >> n;
fact = factfunc(n);
cout << "Factorial of " << n
<< " is " << fact << endl;
return 0;
}
Faculty of Computer Science 21
Inline Functions

• Function call has its overhead (handling the argument, managing


function stack, branch and return).
• For simple and short functions, you may use inline functions to
remove the function call overhead.
• The keyword inline (before the function's return-type) suggest to
the compiler to "expand" the function code in place, instead of
performing a function call.

22
Faculty of Computer Science
// TestInlineFunction.cpp
#include <iostream>
using namespace std;

inline int max(int n1, int n2) {


return (n1 > n2) ? n1 : n2;
}

int main() {
int i1 = 5, i2 = 6;
cout << max(i1, i2) << endl; // inline request to expand to (i1 > i2) ? i1 : i2
return 0;
}
The compiler may expand line 11 as:
cout << (i1 > i2) ? i1 : i2 << endl;

The expanded statement is faster than invoking a function call. The trade-off is
bigger code size.
Faculty of Computer Science 23
Inline Functions
#include <iostream>
using namespace std;
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
int main()
{
float lbs;
cout << "\nEnter your weight in pounds: ";
cin >> lbs;
cout << "Your weight in kilograms is " << lbstokg(lbs) << endl;
return 0;
} Faculty of Computer Science
24
Default Arguments
#include <iostream.h>
void repchar(char='*', int=45);
//void repchar(char repchar='*', int number=45);
int main()
{ repchar();
repchar('=');
repchar('+', 30);
return 0;
}
void repchar(char ch, int n)
{ for(int j=0; j<n; j++)
cout << ch;
cout << endl;
}
25
Faculty of Computer Science
Inline Function vs.
#define Macro
• In C, you can use the #define preprocessor directive to
define a macro with argument, which would then be
expanded during pre-processing.

26
Faculty of Computer Science
/* Test #define macro (TestMacro.cpp) */
#include <iostream>
using namespace std;

#define SQUARE(x) x*x // Macro with argument cout << square(5+5) << endl;
// Okay square(10)
inline int square(int x) { return x*x; } // inline function
cout << SQUARE(x+y) << endl;
// expand to x+y*x+y - wrong answer
int main() {
cout << square(x+y) << endl;
cout << SQUARE(5) << endl; // expand to 5*5 (25) // Okay
// can be fixed using #define SQUARE(x)
(x)*(x)
int x = 2, y = 3; 25
4 cout << SQUARE(++x) << endl;
cout << SQUARE(x) << endl; 35 // expand to ++x*++x (16) - x increment twice
// expand to x*x (4) 100
cout << x << endl; // x = 4
11 cout << square(++y) << endl;
// Problem with the following macro expansions 25 // Okay ++y, (y*y) (16)
16
cout << SQUARE(5+5) << endl; 4 cout << y << endl; // y = 4
// expand to 5+5*5+5 - wrong answer }
16
4
27
More on Preprocessor Directives
• A preprocessor directive begins with # (e.g., "#include <stdio.h>", "#define PI
3.14256295"). When you compile a C/C++ program, these commands will be pre-
processed to produce the source file for the actual compilation (e.g., to include a
specific header file in this program or to define a certain macro substitution).
• A preprocessor command is NOT a C statement, and it does NOT end with a semi-
colon.

#include: #include is most commonly-used to include a header file into this source file
for subsequent compilation. The syntax is as follows:

// Syntax
#include header_file

// Examples
#include <stdio.h> // Search the compiler's include paths
#include "myHeader.h" // Search the current directory first
Faculty of Computer Science 28
More on Preprocessor Directives
// Examples
#include <stdio.h> // Search the compiler's include paths
#include "myHeader.h" // Search the current directory first

#define: #define can be used to define a macro. When the macro pattern
appears subsequently in the source codes, it will be replaced or substituted by
the macro's body. Macro may take parameters.
#undef : You can use #undef to un-define a macro.

// Define a macro substitution


#define marco_name macro_value

// Define a macro with parameters


#define marco_name(args) marco_definition
Faculty of Computer Science 29
More on Preprocessor Directives
// Un-define a macro name
#undef marco_name

// Example
#define PI 3.14159256

// Example
#define square(x) (x*x)
#define max(x,y) ((x > y) ? x : y)
#define REP(i,n) for (i = 0; i < n; ++i)
#define FOR(i,a,b) for (i = a; i < b; ++i)

// Example
#undef PI
Faculty of Computer Science 30
More on Preprocessor Directives
Two common mistakes when using a #define command for macro substitution
are:

#define PI = 3.14159265 // 1
#define PI 3.14159265; // 2

In case 1, the macro name "PI" is defined to be "= 3.14159265" (with the
leading '=' sign).

In case 2, it is "3.14159265;" (with a tailing ';'). These will certainly trigger


errors in your program during the actual compilation.

#define is also commonly-used in define a macro name with an empty body, to


be used in the conditional directives such as #ifdef and #ifndef.
Faculty of Computer Science 31
More on Preprocessor Directives
#ifdef, #ifndef, #if, #elif, #endif: Conditional directives can be used to control
the sections of program send for compilation:

// if the marco_name is defined


#ifdef macro_name
......
#endif

// if the macro_name is NOT defined


#ifndef macro_name
......
#endif

Faculty of Computer Science 32


More on Preprocessor Directives
// conditional if else
#if expression
......
#elif condition eg. #if 1 (always true), #if 0 (always false)
......
#else
......
#endif

// Examples
#ifndef SIZE
#define SIZE 1000
#endif
...... 33
Faculty of Computer Science
Ellipses (...) can be used as the last parameter
of a function to denote zero or more arguments
of unknown type. The compiler suspends type
checking for these parameters. For example,
int sum(int count, ...) {
#include <iostream> int sum = 0;
#include <cstdarg> // Ellipses are accessed thru a va_list
using namespace std;
va_list lst; // Declare a va_list

int sum(int, ...); // Use function va_start to initialize the va_list,


// with the list name and the number of parameters.
int main() { va_start(lst, count);
cout << sum(3, 1, 2, 3) << for (int i = 0; i < count; ++i) {
endl;
// Use function va_arg to read each parameter from va_list,
// 6 // with the type.
cout << sum(5, 1, 2, 3, 4, 5)
<< endl; // 15 sum += va_arg(lst, int);
}
// Cleanup the va_list.
return 0; va_end(lst); 34
} return sum; }
Variables
• Variables possess a characteristic called the storage class. The most
common storage class is automatic. Local variables have the
automatic storage class.

• Variable Scopes - visibility


– Global variables have static storage class: they exist for the life of
a program. They are also visible throughout an entire file
– Static local variables exist for the life of a program but are visible
only in their own function.

Faculty of Computer Science 35


Local Variables
void somefunc()
{ int somevar;
float othervar;
somevar=10; //OK
othervar=11; //OK
nextvar=12; //illegal
}
void otherfunc()
{ int nextvar;
somevar=20; //illegal
othervar=21; //illegal
nextvar=22; //OK
} Faculty of Computer Science 36
Global Variables
#include <iostream> void getachar()
using namespace std; {
#include <conio.h> ch = getch();
char ch = 'a'; }
void getachar();
void putachar(); void putachar()
int main() {
{ cout <<ch;
while( ch != '\r' ) }
{ getachar();
putachar();
}
cout << endl;
return 0;
Faculty of Computer Science 37
}
Static Local Variables
#include <iostream> float getavg(float newdata)
using namespace std; {
float getavg(float); static float total = 0;
int main() static int count = 0;
{ float data=1, avg; count++;
while( data != 0 ) total += newdata;
{ return total / count;
cout << "Enter a number: "; }
cin >> data;
avg = getavg(data);
cout << "New average is " << avg
<< endl;
}
return 0;
Faculty of Computer Science 38
}
Summary of Variable Scopes

Faculty of Computer Science 39


Scope Resolution Operator
• The symbol :: is known as scope resolution operator.
• If a global variable is hidden by a local variable of the same name
(of course not recommended), could use the scope resolution operator
to retrieve the hidden global variable. For example,
// TestScopeResolutionOperator.cpp
float x = 55.5f;
#include <iostream>
using namespace std; // Local
cout << x << endl;
// Global variable
// Use unary scope resolution operator
int x = 5; //to retrieve the global variable

int main() { cout << ::x << endl;

// A local variable having the Same return 0;


//name as a global variable, }
// which hides the global variable 40
Passing Arrays to Functions
// salefunc.cpp
// passes array as argument

#include <iostream>
#include <iomanip> //for setprecision, etc.
using namespace std;

const int DISTRICTS = 4; //array dimensions


const int MONTHS = 3;
void display( double[DISTRICTS][MONTHS] ); //declaration

int main()
{ //initialize two-dimensional array
double sales[DISTRICTS][MONTHS]
= { { 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 }, Faculty of Computer Science 41
{ 12838.29, 2332.63, 32.93 } };
display(sales); //call function; array as argument
cout << endl;
return 0;
} //end main
//--------------------------------------------------------------
//display()
//function to display 2-d array passed as argument
void display( double funsales[DISTRICTS][MONTHS] )
{
int d, m;
cout << “\n\n”;
cout << “ Month\n”;
cout << “ 1 2 3”;
for(d=0; d<DISTRICTS; d++)
{
cout <<”\nDistrict “ << d+1;
for(m=0; m<MONTHS; m++)
cout << setiosflags(ios::fixed) << setw(10)
<< setiosflags(ios::showpoint) << setprecision(2)
<< funsales[d][m]; //array element
} //end for(d)
Faculty of Computer Science 42
} //end display
Command Line Arguments
• May include arguments in the command-line, when running a
program.

• Each of the argument is a string, all the arguments form a string array,
and passed into the main( ) function of the program.

• To process command-line argument, the main( ) function shall use this


header:

int main(int argc, char *argv[ ]) { ...... }

• The second parameter char *argv[ ] captures the string array, while the
first parameter capture the size of the array, or the number of
arguments.
Faculty of Computer Science 43
/*
* Arithmetic.cpp
* Usage: Arithmetic num1 num2 operator
*/
#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[]) {

if (argc != 4) {
cout << "Usage: Arithmetic num1 num2 operator" << endl;
exit(1);
}

int operand1 = atoi(argv[1]); // Parse string to int


int operand2 = atoi(argv[2]); // Parse string to int
char op = argv[3][0]; // Extract first character only

Faculty of Computer Science 44


switch (op) {
case '+':
cout << operand1 << " + " << operand2 << " = "
<< operand1 + operand2 << endl;
break;
case '-':
cout << operand1 << " - " << operand2 << " = "
<< operand1 - operand2 << endl;
break;
case '*':
cout << operand1 << " * " << operand2 << " = "
<< operand1 * operand2 << endl;
break;
case '/':
cout << operand1 << " / " << operand2 << " = "
<< operand1 / operand2 << endl;
break;
default:
cout << "Unknown operator" << endl;
exit(1);
}
Faculty of Computer Science 45
return 0; }
To set command line argument
to Codeblock project

1. Select the project name

2. Click “Set Programs’


Arguments” from Project
menu

3. Type arguments and separate


with space in each arguments
in Program Arguments
Section

4. Click Ok
Faculty of Computer Science 46
Summary
• Functions provide a way to help organize programs, and to reduce program
size, by giving a block of code a name and allowing it to be executed from
other parts of the program.

• Function declarations (prototypes) specify what the function looks like,


function calls transfer control to the function, and function definitions
contain the statements that make up the function.

• The function declarator is the first line of the definition.

• Arguments can be sent to functions either by value, where the function


works with a copy of the argument, or by reference, where the function
works with the original argument in the calling program.

• Functions can return only one value. Functions ordinarily return by value,
but they can also return by reference, which allows the function call to be
used on the left side of an assignment statement.

• Arguments and return values can be either simple data types or structures.
Faculty of Computer Science 47
Summary

• An overloaded function is actually a group of functions with the same name.


Which of them is executed when the function is called depends on the type
and number of arguments supplied in the call.

• An inline function looks like a normal function in the source file but inserts
the function’s code directly into the calling program.

• Inline functions execute faster but may require more memory than normal
functions unless they are very small.

• If a function uses default arguments, calls to it need not include all the
arguments shown in the declaration. Default values supplied by the function
are used for the missing arguments.

Faculty of Computer Science 48


Summary
• Variables possess a characteristic called the storage class. The most common
storage class is automatic.
• Local variables have the automatic storage class: they exist only while the
function in which they are defined is executing. They are also visible only
within that function.
• Global variables have static storage class: they exist for the life of a
program. They are also visible throughout an entire file.
• Static local variables exist for the life of a program but are visible only in
their own function.
• A function cannot modify any of its arguments that are given the const
modifier.
• A variable already defined as const in the calling program must be passed as
a const argument.
Faculty of Computer Science 49
Faculty of Computer Science 50

You might also like