C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
Chapter 2
Procedural
Programming
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Preview
Basic concepts that are similar in both Java and C++, including:
•standard data types
•control structures
•I/O
•functions
Dynamic memory management, and some basic pointer
operations.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Main function
Java C++ Comments about
C++
class C {
public static void
main(String args[])
{
...
}
int main() {
...
return 0;
}
The main function is not included in any class.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Comments
Comments about C++
/*
...
*/
//
C++ does not provide the Java comment/** ... */,
used to create documentation
Remember about programming guidelines!
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Primitive Data Types
Comments about C++
char charis one byte long and does not use Unicode
short
int
long
float
double
The language does not define the size and range of numeric
primitive data types, which are implementation dependent.
There are no predefined wrapper classes for primitive data
types.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: More Primitive Data Types
string language = "C" + "++";
bool mark = language < "Java";
char first = language[0];
Java C++ Comments about C++
byte -- similar to unsignedchar
boolean bool Any non- zero numeric value can be treated as true,
a zero value can be treated as false
String string
To use strings you must include the <string>library
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: typedefand sizeof
Asynonymfor an existing type:
typedefbool Boolean;
Sizeof data type(in bytes):
int k = 5;
... sizeof(int)... sizeof k …
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Variables, Constants and
Expressions
constint LINES = 25;
Comma operator, e.g. e1, e2
for(i = 1, j = 2; i < N && j < M; ++i, ++j)
...
Java C++
final const --
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Type Conversions
•between booland int
•Implicit type conversionsor castsare performed when:
the value is promotedto a more precise type:
double d = 3; // 3 is promoted to 3.0
the value is demoted, resulting in a loss of precision:
double d = 3.14159;
int i = d; // 3.14159 is demoted
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Type Conversions (cont.)
Better to use explicit cast:
i = static_cast<int>(d);
Example
int i, j;
... // initialization of i and j
double d = static_cast <double>(i) / j;
// avoids int division
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Type Conversions (cont.)
•Conversion to remove constness,which allows a const
identifier to be modified:
const int i = 3;
const_cast<int>(i) = 1; // not constant
•reinterpret_castused to perform a low-level
reinterpretation of the bit pattern to force the type conversion
•dynamic_castused for derived classes
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Control Structures
Comments about C++
Conditional and switch
statements
same
Loops breakor continue cannot be
labeled. A gotostatement is
available (if and when really needed).
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Basic I/O
Three predefined streams:
•cout-the standard output stream
<<(put-to) binary operator is used for output
•cin -the standard input stream
>>(get from) operator is used for input
•cerr-the standard error stream.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Basic I/O (cont.)
cout << "Enter value "; // prompt
int i;
cin >> i; // input integer
cout << "The value is:";
cout << i; // output integer
cout << "The value is:" << i << endl; // chain
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
Example of I/O
// File ex2.1.cpp
// Read integer values until a positive value is entered
// If a non- integer value is entered, abort the program
// Otherwise, output the integer value
#include <iostream>
int main() {
int i = 0;
bool correct = false;
cout << "Enter a positive integer value" << endl;
while(cin >> i) {
if(i > 0) {
correct = true;
break;
}
cout << "non- positive value; re- enter" << endl;
}
if(!correct)
cout << "incorrect integer value" << endl;
else cout << "You entered " << i << endl;
}
test for correct input
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Arrays
C++ arrays are borrowed from C:
The C++ standard library also provides vectors.
Java C++ Comments about C++
int [] marks =
new int[10]
int
marks[10]
-lower bound equal to zero
-size must be known at
compile time
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Reference Data Types
A reference data type(which differs from Java references) is of the
form
type&
It is used for:
•passing parameters and returning values
•providing an aliasin a variable definition (must be initialized in
the definition)
int i = 1;
int& pi = i; // pi is an alias for i
pi++; // now i is 2, pi not changed
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Reference Data Types
(cont.)
References must be initialized with expressions that are lvalues.
You can declare the reference as constant; for example:
const int& cpi = 8;
(may be initialized with expressions that are not lvalues).
Mostly used with parameters.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions
Terminology:
an expression that appears in a function call, such as xin f(x), is
called an actual parameter, as opposed to the formal parameter
that appears in the function definition.
Construct
Comments about C++
int
foo(pars) {
body
}
C++ allows global functions, that is functions that are defined
outside of any class (also called stand-alonefunctions)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions (cont.)
A function may be defined as inline:
inline int sum(int i, int j) {
return i + j;
}
which is a request to the compiler to generate code inline.
Each call to the inlined function is replaced at compile timeby its body:
int i = sum(1, k);
// replaced by: int i = 1 + k
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Declarations and
Definitions
A function declarationmerely provides a function signature and the
return type:
bool prime(int); // note the semicolon
A function definitionincludes the declaration and the implementation of
the function. A function can be called onlyif it has been declared or
defined.
Each function declaration must come with the documentation to be used
by the client. A different kind of information is needed by the
implementor of the function, and so the function definition comes
with its own documentation.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pass by Value, Pass by
Reference, and Constant Pass
by Reference
Passing parameters by value means that the formal parameter is assigned
the valueof the actual parameter, and the actual parameter is not
modified:
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int i = 1;
int j = 2;
swap(i, j);
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pass by Value, Pass by
Reference, and Constant Pass
by Reference
Passing by reference allows the function to modify the actual
parameter. The type of the parameterpassed by reference is a
reference type, with an &following the parameter type:
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int i = 3;
int j = 4;
swap(i, j); // i and j passed by reference
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pass by Value, Pass by
Reference, and Constant Pass
by Reference
Constant pass by referencedoes not allow the client to inadvertently
modify the actual parameter:
double product(const double&block, int size);
If a function has a non-constant parameter, then it may notbe called with
a constant actual parameter.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
If you do notwant tomodify the value of the actual parameter,
then use
-pass by valuefor parameters of primitive data types,
-constant pass by referencefor parameters of structured data
types, such as classes.
If you dowant to modify the value of the actual parameter, then use
pass by reference
.
Pass by Value and by
Reference
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Default Values of
Parameters
A default valueof a formal function parameter is useful if this function
is frequently called with the same actual parameter.
The client can call this function either without the actual parameter for
this formal parameter (and so using the default value), or with an
actual parameter to override the default value.
A function move()that typically moves to position 0by a step of 1
void move(int from, int to = 0, int by = 1);
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Default Values of
Parameters (cont.)
Only trailingparameters may be assigned default values:
void move(int from, int to = 0, int by);
Overriding values of the actual parameters are assigned from left to right:
void move(int from, int to = 0, int by = 1);
move(2); // move(2, 0, 1)
move(2, 3); // move(2, 3, 1)
move(2, 3, 4); // move(2, 3, 4)
It is not possible to override the second most trailing default parameter,
without overriding the first default parameter.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Overloading Functions
The nameof a function should identify the action performed by this
function.
Overloading a function means that you can have several functions with
the same name in a single scope, provided that these functions have
differentsignatures:
double max(double, double);
int max (int, int); // overloaded
bool max(int, int); // identical signatures
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Overloading Functions
(cont.)
Sometimes, overloading can be replaced by using default parameter
values:
void move(int from, int to);
void move(int from, int to, int by);
can be replaced by a single function:
void move(int from, int to, int by = 0);
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions and Arrays
When arrays are used as function parameters, their size has to be passed
as another parameter:
void maxMin(const double arr[], int size,
double&max, double& min) {
int i;
for(max = min = arr[0], i = 1; i < size; ++i) {
if(max < arr[i])
max = arr[i];
if(min > arr[i])
min = arr[i];
}
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions and Arrays
(cont.)
double arr[] = {1.3, 1.2, 1.1};
double maxi, mini;
maxMin(arr, 3, maxi, mini);
Consider a different maxMin1():
const double x[] = {3, 1, 7.8};
void maxMin1(double arr[],int size,
double& max, double& min);
maxMin1(x, 3, max, min); // error, x is const
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions Returning
References
A function may return a reference type, and if so, a function call is an
lvalue:
int a[5];
int&index(int x[], int i) {
// gives read/write access
// to the i-th element of x
return x[i];
}
cin >> index(a, 1);
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions Returning
Constant References
Functions may also be designed to provide read-only access, by
returning a constantreference:
const int&get(const int x[], int i) {
return x[i];
}
cout << get(a,2);
cin >> get(a,1); // can't change the value
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management
•Static memoryis used to store the values of global variables, as well
as function and class static variables.
•Stack-basedmemory is implicitly managed by function calls and
function returns.
•Heap-basedmemory is used to dynamically manage memory as a
result of a program’s request, such as Java's newcall.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management (cont.)
•Dynamic memory allocationmeans that a block of memory
requested by a program is removed from the heap, and can be used by
this program.
•Dynamic memory deallocationmeans that a program returns a block
of memory to the heap -the de-allocated memory can be used the next
time a memory request occurs.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management (cont.)
Garbage collectordecides when inaccessibleobjects are deallocated.
Java objects are alwaysallocated on the heap and never on the run- time
stack, and all memory deallocation is done automatically by the
garbage collector.
Memory leakage occurs when memory that is no longer needed by the
program has not been freed and made available for reuse.
What's a reference to an object in Java? It is a memory address;
specifically, the address of a block of memory allocated for this object
on the heap.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management (cont.)
In C++:
•objects may be allocated both on the stack and in the heap
•there is no standardgarbage collector
•the programmer is fully responsible for explicitly deallocating
memory.
This may lead to various programming errors:
•dangling reference problem -the result of a variable referencing a
memory block whose lifetime has expired (allocated on the stack and then deallocated)
•memory leakage.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Basic Pointers Operations
Pointer variables, or just pointers have names, types, and values.
The valueof a pointer is the address of a memory block.
The typeof a pointer determines the size of that block (the size is
essential to access data stored at that address).
For any data type T, for example int, you can define a variable of type
"pointer to T", such as "pointer to int“:
int*p; // pointer to int
char*s; // pointer to char
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Basic Pointers Operations
(cont.)
Dereferencing–using pointer’s name, prefixed with the asterisk *.
For example, *p is the contents of the memory block that ppoints to,
and *pbehaves as an intvariable.
You can take a non- pointer variable and get a pointer by applying the
address operator&to it:
int i = 1;
...i... // an int variable
...&i... // like int pointer, pointing to i
int* p;
p = &i; // p points to i
... *p... // dereferenced p is equal to i
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Basic Pointers Operations
(cont.)
C++ provides NULL, but rather than using it, use 0
Two common errors associated with C++ pointers is the use of
•un-initialized pointers,
•pointers that point to 0.
The language's run- time system does not provide the same safety as
Java's exception handling mechanism; instead, your program may
continue to execute following the use of an un- initialized pointer, and
crash unexpectedly at a later time.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Constant Pointers
Read these pointer declarations right-to-left:
const int* p;
a pointer to an integer that is constant; the value of pmay change,
but the value of *pcannot
int* const cp;
a constant pointer to integer; the value of *cpcan change,
but the value of cpcannot
const int* const cpc;
a constant pointer to a constant integer.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Constant Pointers (cont).
In some exceptional cases you may want to remove const'ness:
const_cast<type >(value)
For example, to make pointer p
const int* p;
point to the value 3(i.e. to assign 3 to *p), you can use
*(const_cast<int*>(p)) = 3;
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Pointers as Parameters
Array parameters are treated like pointers.
void maxMin(double* arr, int size, double& max,
double& min);
void maxMinConst(const double* arr, int size,
double& max, double& min);
constdouble a[] = {1.5, 3.1};
double max, min;
maxMin(a, 2, max, min); // a is const
maxMinConst(a, 2, max, min);
maxMin(const_cast<double*>(a), 2, max, min);
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
1. Functions that do not modify values pointedto by their pointer
parameters should have these parameters specified as const; for
example, const double*.This allows us to call the function
both with non- constant and constant pointer parameters.
2. Functions that modify their pointer parametersshould have these
specified as passed by reference.
Pointer Parameter
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Functions Returning
Pointers
int*change(int arr[], int size, int i) {
// return a pointer to the i- th element
if(i < 0 || i >= size)
return 0;
return &arr[i];
}
const int*nonChange (const int arr[], int size, int i);
... // as above
int x[] = {1, 2, 3};
int*i = change(x, 3, 2);
*i = 3; // OK, can modify through i
const int*j = nonChange(x, 3, 2);
cout << *j;
*j = 3; // can't assign to a const
i = nonChange(x, 3, 2); // can't: non- const
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: C-style Strings and main
Function Parameters
C++ provides two kinds of strings:
string
char*-pointer to char, (C-style)
C-style strings cannot be avoided in the main function, and for file
operations
A C-style string can be passed as a parameter of a function:
int foo(char* str);
Within the body of this function, stris treated as an array of characters
(terminated by the zero character). The size of this array is the length
of the string, which can be obtained by using the strlen()
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: C-style Strings and main
Function Parameters
The name of the program is taken from the command line as argv[0],
and therefore argcis always greater than zero
Java
C++ Comments about C++
void main(
String[]
args)
int main(
int argc,
char*argv[])
Integer function with two parameters:
-the number of command line
parameters
-an array of C-style strings representing
parameters
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: C-style Strings and main
Function Parameters
// File: ex2.5.cpp
// Copy words from the input file to the output
// file; passing filenames on the command line
// Output the total number of words to the standard output
// Return 1 if can't open input file;
// 2 if can't open output file
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[]) {
// check command line
if(argc != 3) {
cerr << "Usage: " << argv[0] << " file1 file2" << endl;
return 1;
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
ifstream inFile(argv[1]);
if(!inFile) {
cerr << "can't open " << argv[1] << endl;
return 1;
}
ofstream outFile(argv[2]);
if(!outFile) {
cerr << "can't open " << argv[2] << endl;
return 2;
}
string word; // copy words
long wordCounter = 0;
while(inFile >> word) { // end- of-file
outFile << word << endl;
wordCounter++;
}
cout << "Read " << wordCounter << " words" << endl;
return 0;
}
Example
ifstream
and
ofstream
constructors
use C-style
strings
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Static Local Variables
Local variables in a function are allocated on the stack, in the so-
called instance, or frame for this function. It is sometimes useful
to limit the scopebut not the lifetime of a variable.
void login() {
static int counter = 0;
counter++;
…
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: File Organization and
Standard Facilities
A Java program:
•typically consists of multiple files
•when you compile it, you usually use the name of single file,
which contains the main function to be invoked.
•the Java compiler checks what other files are needed, and whether
these files have been recently compiled. All files that have been
modified since the last compilation are recompiled, and finally,
all compiled files are linked.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: File Organization and
Standard Facilities (cont.)
A C++ program:
•is a set of compilation units, which must be linked together to
form the executable code
•typically consists of multiple files; each file is a unit of
compilation.
•the programmer is responsible for compiling all the necessary
files
•you typically use separate compilation, and a tool such as make
to update the executable code.
Separate compilation: you can compile parts of your program,
where each part is a file
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Preprocessing and Header
Files
Related function declarationsare typically stored in headerfiles.
You typically include the header file containing required
declarations.
Any line of C++ code that begins with the # (pound symbol) is
referred to as a preprocessorcommand line:
includecommand, which is used to include external files in the
current file
conditional compilationcommand, which tells the compiler that a
partof the source file is included conditionally
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Preprocessing and Header
Files (cont.)
Standardheader files
#include <filename>
User-definedheader files:
#include "filename.h"
(User-defined header file typically have the ‘h’ extension, for
example "screen.h".)
These two formats differ in how the specified file is located by the
compiler.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Preprocessing and Header
Files (cont.)
Conditional compilation directiveis based on the definition of a
name, called a macro, which specifies whether this file has
already been included. By convention, an include file screen.h
will have the macro name SCREEN_H. The header file might look
like this:
#ifndefSCREEN_H // conditional compilation
#defineSCREEN_H
... // contents of the header file
#endif
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
The header file should be conditionally included; for example
#ifndef SCREEN_H // conditional compilation
#define SCREEN_H
... // contents of the header file
#endif
Include Guards
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright:Addison-Wesley Publishing Company, 2002
2: Namespaces
To avoid name collisions, C++ provides namespaces, (similar to
Java's packages):
Each namespace defines a new scope, and a name used in one
namespace does not conflict with the same name used in another
namespace.
The C++ standard library is defined in a namespace called std.
Practically, in all programs, you include the header file:
#include <iostream>
In order to make every name from this namespace directly available,
you specify the namespace with the using keyword:
using namespace std;