Lecture7 - Function Using in Conceptual Organization of A Program
Lecture7 - Function Using in Conceptual Organization of A Program
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
22
Faculty of Computer Science
// TestInlineFunction.cpp
#include <iostream>
using namespace std;
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.
// 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).
// 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
#include <iostream>
#include <iomanip> //for setprecision, etc.
using namespace std;
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.
• 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;
if (argc != 4) {
cout << "Usage: Arithmetic num1 num2 operator" << endl;
exit(1);
}
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.
• 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 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.