❖ Parametrizing functions ▪ Using parameters of different types • Arithmetic type parameters The basics of functions... ❖ Parametrizing functions ▪ Using parameters of different types •
Trang 1KỸ THUẬT LẬP TRÌNH HỆ CƠ ĐIỆN TỬ Programming Engineering in Mechatronics
1
Giảng viên: TS Nguyễn Thành Hùng Đơn vị: Bộ môn Cơ điện tử, Viện Cơ khí
Hà Nội, 2020
Trang 2Chapter II Modular programming in C++
• Structured programming relies on top-down design.
• In C and C++ languages, the smallest structural unit having
independent functionality is called function.
• If functions or a group of functions belonging together are
put in a separate module (source file), modular
programming is realised
• Structural programming also contributes to creating new
programs from achieved modules (components) by
bottom-up design.
• This chapter aims to introduce the modular and procedural programming in C++.
Trang 3❖ How to use functions on a more professional level?
❖ Namespaces and storage classes
❖ Preprocessor directives of C++
Trang 4Chapter II Modular programming in C++
❖ The basics of functions
❖ How to use functions on a more professional level?
❖ Namespaces and storage classes
❖ Preprocessor directives of C++
Trang 6The basics of functions
• In C++, a function is a unit (a subprogram) that has a name and that can
be called from the other parts of a program as many times as it is
needed.
• In order to use a function efficiently, some of its inner variables
(parameters) are assigned a value when the function is called
• When a function is called (activated), the values (arguments) to be
assigned to each parameter have to be passed in a similar way.
• The called function passes control back to the place where it was called
by a return statement
• The value of the expression in the return statement is the return
value returned back by the function, which is the result of the function
call expression.
Trang 8The basics of functions
❖ Defining, calling and declaring functions
• The general form of a function definition is the following (the
signs 〈 〉 indicate optional parts):
Function definition
Trang 99
Trang 10The basics of functions
❖ Defining, calling and declaring functions
• The steps of calling a function
function_name ( 〈argument 1 , argument 2 , … argument n〉)
Steps of calling a function
Trang 11• C++ standards require that functions have to be declared before
they are called
Function declaration
Function definition
Trang 12The basics of functions
❖ Defining, calling and declaring functions
• The complete declaration of a function (its prototype ):
return_value function_name(〈parameter declaration list〉);
return_value function_name(〈type_list〉);
declaration C interpretation C++ interpretation
type funct(); type funct( ); type funct(void);
type funct( ); type funct( ); type funct( );
type funct(void); type funct(void); type funct(void);
Trang 13• C++ makes it possible that a parameter list containing at least one parameter
should end with three dots ( )
• The transferring (throw) of exceptions to the caller function can be enabled or
disabled in function header
return_type function_name (〈parameterlist〉) 〈throw(〈type_list〉)〉
Trang 14The basics of functions
❖ The return value of functions
• The return_type figuring in the definition/declaration of a function
determines the return type of the function, which can be of any C++ type with the exception of arrays and functions.
Trang 15• By using the type void, we can create functions that do not
return any value
Trang 16The basics of functions
❖ The return value of functions
• Functions can return pointers or references
Trang 17• A parameter can be scalar (bool, char, wchar_t, short, int, long, long long,
float, double, enumeration, reference and pointer) or structure, union, class
or array.
The general form of polynomials:
Horner's scheme
Trang 18The basics of functions
❖ Parametrizing functions
▪ Parameter passing methods
• Passing parameters by value
Trang 19▪ Parameter passing methods
• Passing parameters by value
Trang 20The basics of functions
❖ Parametrizing functions
▪ Parameter passing methods
• Passing parameters by reference
Trang 21▪ Parameter passing methods
• Passing parameters by reference
Trang 22The basics of functions
❖ Parametrizing functions
▪ Parameter passing methods
• Passing parameters by reference
Trang 23▪ Using parameters of different types
• Arithmetic type parameters
Trang 24❖ Parametrizing functions
▪ Using parameters of different types
• Arithmetic type parameters
The basics of functions
Trang 25▪ Using parameters of different types
• User-defined type parameters
Trang 26❖ Parametrizing functions
▪ Using parameters of different types
• User-defined type parameters
The basics of functions
Trang 27▪ Using parameters of different types
• Passing arrays to functions
Trang 28❖ Parametrizing functions
▪ Using parameters of different types
• Passing arrays to functions
The basics of functions
Trang 29▪ Using parameters of different types
• Passing arrays to functions
Trang 30❖ Parametrizing functions
▪ Using parameters of different types
• Passing arrays to functions
The basics of functions
Trang 31▪ Using parameters of different types
• Passing arrays to functions
Trang 33▪ Using parameters of different types
• String arguments
Trang 35▪ Using parameters of different types
• String arguments
Trang 37▪ Using parameters of different types
• Functions as arguments
Trang 39▪ Using parameters of different types
• Variable length argument list
Trang 40The basics of functions
❖ Parametrizing functions
▪ Using parameters of different types
• Variable length argument list
Trang 41▪ Using parameters of different types
• Parameters and return value of the main() function
Trang 42❖ Parametrizing functions
▪ Using parameters of different types
• Parameters and return value of the main() function
Providing command line
arguments
The basics of functions
Trang 43▪ Using parameters of different types
• Parameters and return value of the main() function
In a console window In a development environment
C:\C++Book> command1 first 2nd third
C:\C++Book>
Trang 44❖ Parametrizing functions
▪ Using parameters of different types
• Parameters and return value of the main() function
The basics of functions
Trang 45▪ Using parameters of different types
• Parameters and return value of the main() function
Wrong number of parameters:
command2
Correct number of parameters:
command2 alfa beta
Wrong number of parameters!
Usage: command2 arg1 arg2
Correct number of parameters: 1 argument: alfa 2 argument: beta
Trang 46❖ Defining, calling and declaring functions
❖ The return value of functions
❖ Parametrizing functions
❖ Programming with functions
The basics of functions
Trang 47▪ Exchanging data between functions using global variables
Trang 48❖ Programming with functions
▪ Exchanging data between functions using global variables
• Solution for above example
The basics of functions
Trang 49▪ Exchanging data between functions using global variables
• Solution for above example
Trang 50❖ Programming with functions
▪ Exchanging data between functions using parameters
The basics of functions
Trang 51▪ Exchanging data between functions using parameters
Trang 52❖ Programming with functions
▪ Exchanging data between functions using parameters
The basics of functions
Trang 53▪ Implementing a simple menu driven program structure
Trang 55▪ Recursive functions
• Fibonacci numbers:
more efficient
Trang 56❖ Programming with functions
▪ Recursive functions
• greatest common divisor (gcd):
The basics of functions
Trang 57▪ Recursive functions
• binomial numbers:
Trang 59▪ Recursive functions
Trang 60Chapter II Modular programming in C++
❖ The basics of functions
❖ How to use functions on a more professional level?
❖ Namespaces and storage classes
❖ Preprocessor directives of C++
Trang 61❖ Overloading (redefining) function names
❖ Function templates
Trang 62❖ Inline functions
• C++ compilers decrease the time spent on calling the functions
marked with the keyword inline.
• This solution is recommended to be used for small-sized and
frequently called functions
How to use functions on a more professional level?
Trang 6363
Trang 65• Different functions can be defined with the same name and
within the same scope but with a different parameter list.
Trang 66❖ Overloading (redefining) function names
How to use functions on a more professional level?
Trang 67❖ Overloading (redefining) function names
❖ Function templates
Trang 68❖ Function templates
▪ Creating and using function templates
• A template declaration starts with the keyword template,
followed by the parameters of the template enclosed within the
signs < and >
How to use functions on a more professional level?
Trang 69▪ Creating and using function templates
Trang 70❖ Function templates
▪ Creating and using function templates
How to use functions on a more professional level?
Trang 71▪ Function template instantiation
• A function template can be instantiated in an explicit way as well
if concrete types are provided in the template line containing the
header of the function:
Trang 72❖ Function templates
▪ Function template specialization
How to use functions on a more professional level?
Trang 73▪ Some further function template examples
Trang 74❖ Function templates
▪ Some further function template examples
How to use functions on a more professional level?
Trang 75▪ Some further function template examples
Trang 76Chapter II Modular programming in C++
❖ The basics of functions
❖ How to use functions on a more professional level?
❖ Namespaces and storage classes
❖ Preprocessor directives of C++
Trang 77❖ Storage classes of functions
❖ Modular programs in C++
❖ Namespaces
Trang 78❖ Storage classes of variables
▪ A storage class:
• defines the lifetime or storage duration of a variable,
• determines the place from where the name of a variable can be
accessed directly – visibility, scope – and also determines which name designates which variable – linkage
▪ A storage class (auto, register, static, extern) can be assigned to
variables when they are defined
Namespaces and storage classes
Trang 7979
Trang 80❖ Storage classes of variables
▪ Accessibility (scope) and linkage of variables
• In a C++ source code, variables can have one of the following scopes:
block
level
A variable of this type is only visible in the block (function block) where it has been defined so its accessibility is local
If a variable is defined on a block level without the storage classes extern and static,
it does not have any linkage.
Namespaces and storage classes
file level
A file level variable is only visible in the module containing its declaration
Identifiers having file level scope are those that are declared outside the functions
of the module and that are declared with internal linkage using the static storage
class.
program
level
A program level variable is accessible from the functions of all the modules (all
compilation units) of a program
Global variables that are declared outside the functions of a module (that is
with external linkage) have program level scope.
Trang 81Variable scopes
Trang 82Within blocks, variables defined without the static storage class and
the parameters of functions have automatic (local) lifetime
dynamic
lifetime
Independently of their storage classes, memory blocks that are
allocated by the operator new and deallocated by the operator delete have dynamic lifetime.
Trang 83▪ Storage classes of block level variables
• Automatic variables: Automatic variables are created when
control is passed to their block and they are deleted when that block is exited
Trang 84❖ Storage classes of variables
▪ Storage classes of block level variables
• The register storage class: The register storage class can only be
used for automatic local variables and function parameters
Namespaces and storage classes
Trang 85▪ Storage classes of block level variables
• Local variables with static lifetime
Trang 86❖ Storage classes of variables
▪ Storage classes of file level variables
Namespaces and storage classes
Trang 87▪ Storage classes of program level variables
Same definitions (only one of them can
double sum;
double sum = 0;
extern double sum = 0;
extern double sum;
int vector[12];
extern int vector[12] = {0};
extern int vector[];
extern int vector[12];
extern const int size = 7; extern const int size;
Trang 88❖ Storage classes of variables
❖ Storage classes of functions
❖ Modular programs in C++
❖ Namespaces
Namespaces and storage classes
Trang 89Definitions (only one of them can be used) Prototypes
double GeomMean(double a, double b) {
return sqrt(a*b); }
extern double GeomMean(double a,
double b) { return sqrt(a*b); }
double GeomMean(double, double);
extern double GeomMean(double,
Trang 90❖ Storage classes of functions
Namespaces and storage classes
Trang 91• Accessing the compiled C functions from within C++ source: use
the extern "C" declaration.
Trang 92❖ Storage classes of variables
❖ Storage classes of functions
❖ Modular programs in C++
❖ Namespaces
Namespaces and storage classes
Trang 9393
Trang 94❖ Modular programs in C++
Namespaces and storage classes
Trang 95❖ Storage classes of functions
❖ Modular programs in C++
❖ Namespaces
Trang 96❖ Namespaces
▪ The default namespaces of C++ and the scope operator
• C++ enclose Standard library elements in the namespace
called std.
• In order to be able to refer the elements of a namespace, we
have to know how to use the scope operator (::)
• With the help of :: operator, we can refer names having file and
program level scope (that is identifiers of the global namespace)
from any block of a program
Namespaces and storage classes
Trang 97▪ The default namespaces of C++ and the scope operator
Trang 99▪ Creating and using user-defined namespaces
• Accessing the identifiers of a namespace
Directly by using the scope operator: Or by using the directive using namespace:
Trang 100❖ Namespaces
▪ Creating and using user-defined namespaces
• Accessing the identifiers of a namespace
Or by providing using -declarations:
Namespaces and storage classes
Trang 101▪ Creating and using user-defined namespaces
• Nested namespaces, namespace aliases:
Trang 102❖ Namespaces
▪ Creating and using user-defined namespaces
• Nested namespaces, namespace aliases:
Namespaces and storage classes
Trang 103▪ Creating and using user-defined namespaces
• Nested namespaces, namespace aliases:
Trang 104• Anonymous namespaces:
Namespaces and storage classes
Trang 105❖ How to use functions on a more professional level?
❖ Namespaces and storage classes
❖ Preprocessor directives of C++
Trang 106Preprocessor directives of C++
The compilation process in C++
Trang 107❖ Conditional compilation
❖ Using macros
Trang 108#include directives #include <string>
Preprocessor directives of C++
Trang 109Namespaces having an identifier namespace nsrand { }
Variable declarations extern double point[];
inline function definitions inline int Sqr(int a) {return a*a;}
template declarations template <class T> T Sqr(T a);
template definitions template <class T> T Sqr(T a)
{return a*a;}
Trang 110❖ Including files
• definitions of non-inline functions,
• variable definitions,
• definitions of anonymous namespaces
The following elements should never be placed in include files:
Preprocessor directives of C++
Trang 111➢ One part of the elements that can be placed in a header file have
to be included only once in a code
➢ That is why, all header files have to have a special preprocessing
structure based on conditional directives:
Trang 113• The code parts to be compiled under conditions can be selected
in many ways, by using the following preprocessor directives:
#if, #ifdef, #ifndef, #elif, #else and #endif.
Trang 114❖ Conditional compilation
• Instead of the structure above, it is better to use a solution that
examines the definition of the symbol TEST.
Preprocessor directives of C++
Trang 115• Each pair of the following checkings return the same results:
#if defined(TEST) // defined
#endif
#ifdef TEST // defined
#endif
#if !defined(TEST) // not defined
#endif
#ifndef TEST // not defined
#endif