CH 2
CH 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
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Main function
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Comments
/*
... C++ does not provide the Java comment /** ... */,
*/ used to create documentation
//
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Primitive Data Types
char char is one byte long and does not use Unicode
short The language does not define the size and range of numeric
int primitive data types, which are implementation dependent.
long
float There are no predefined wrapper classes for primitive data
double types.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: More Primitive Data Types
Java C++ Comments about C++
String string
To use strings you must include the <string> library
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
Java C++
final const --
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Type Conversions
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.)
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.)
const int i = 3;
const_cast<int>(i) = 1; // not constant
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Control Structures
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Basic I/O
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Basic I/O (cont.)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
// File ex2.1.cpp
// Read integer values until a positive value is entered
// If a non-integerExample of I/O abort the program
value is entered,
// 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) { test for correct input
correct = true;
break;
}
cout << "non-positive value; re-enter" << endl;
}
if(!correct)
cout << "incorrect integer value" << endl;
else cout << "You entered " << i << endl;
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Arrays
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Reference Data Types
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Reference Data Types
(cont.)
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 x in f(x), is
called an actual parameter, as opposed to the formal parameter
that appears in the function definition.
int C++ allows global functions, that is functions that are defined
foo(pars) { outside of any class (also called stand-alone functions)
body
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Functions (cont.)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Declarations and
Definitions
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 reference does not allow the client to inadvertently
modify the actual parameter:
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
Pass by Value and by
Reference
If you do want to modify the value of the actual parameter, then use
pass by reference.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Default Values of
Parameters
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Default Values of
Parameters (cont.)
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)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Overloading Functions
(cont.)
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:
int a[5];
int& index(int x[], int i) {
// gives read/write access
// to the i-th element of x
return x[i];
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Functions Returning
Constant References
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
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management (cont.)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Pointers and Dynamic
Memory Management (cont.)
Java objects are always allocated on the heap and never on the run-time
stack, and all memory deallocation is done automatically by the
garbage collector.
In C++:
• objects may be allocated both on the stack and in the heap
• there is no standard garbage collector
• the programmer is fully responsible for explicitly deallocating
memory.
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Basic Pointers Operations
For any data type T, for example int, you can define a variable of type
"pointer to T", such as "pointer to int“:
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Basic Pointers Operations
(cont.)
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.)
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
const int* p;
a pointer to an integer that is constant; the value of p may change,
but the value of *p cannot
*(const_cast<int*>(p)) = 3;
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Pointers as Parameters
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:
The name of the program is taken from the command line as argv[0],
and therefore argc is always greater than zero
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
ifstream inFile(argv[1]); and
if(!inFile) {
Example ofstream
cerr << "can't open " << argv[1] << endl; constructors
return 1; use C-style
} strings
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;
}
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Static Local Variables
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.
Any line of C++ code that begins with the # (pound symbol) is
referred to as a preprocessor command line:
include command, which is used to include external files in the
current file
conditional compilation command, which tells the compiler that a
part of 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.)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Preprocessing and Header
Files (cont.)
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
Include Guards
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002
2: Namespaces
C++ Programming with Design Patterns Revealed Tomasz Müldner Copyright: Addison-Wesley Publishing Company, 2002