How to Program in C++
How to Program in C++
You may copy this file for noncommercial use. The latest version is located at cs.fit.edu/~mmahoney/cse2050/how2cpp.html updated Apr. 14, 2010. Please report errors to Matt Mahoney at [email protected]. Seldom-used features have been deliberately omitted.
Language Summary
Statements if, for, while, return, break...
Expressions arithmetic, comparison, assignment...
The most important types are int, char, bool, double, and the containers string, vector, and map. Summary of common types:
Built-in Description
int x; Fastest integer type (16-32 bits), also short, long, unsigned
char x; 8-bit character, '\0' to '\xFF' or -128 to 127
double x; 64 bit real + or - 1.8e308, 14 significant digits, also float
bool x; true or false
Modifiers Description
const T x; Non-modifiable object
T& y=x; Reference, y is an alias for x, which both have type T
T f(...) {...} Defines f as a function returning T
T* p; Pointer to T (*p is a T object)
T a[N]; Array of N elements of T, a[0] to a[N-1]
static T x; Place x in data segment
register T x; (rare) Hint to optimize for speed
volatile T x; (rare) x may be modified externally
The following standard library types and functions require at the beginning of the program:
#include <header>
using namespace std;
Library Type Description Header
istream Standard input (cin) iostream
ostream Output (cout, cerr, clog) iostream
ifstream Input file fstream
ofstream Output file fstream
string Sequence of char string
vector<T> Expandable array/stack of T vector
deque<T> Array/double ended queue deque
list<T> List/stack/queue of T list
map<T1,T2> Associative mapping of T1 to T2 map
set<T1> A map with keys only set
pair<T1,T2> Two objects of type T1 and T2 map or utility
priority_queue<T> Sorted queue queue
stack<T> Stack stack
bitset<N> Array of N bool with logical operations bitset
valarray<T> Array with arithmetic operations valarray
complex<T> Complex number complex
iterator Pointer into a container (Included with container)
const_iterator Pointer not allowing element assignment (Included with container)
exception Hierarchy of exception types stdexcept, exception
C++ Standard Library Functions Header
min(), max(), swap(), sort(), copy(), equal() algorithm
accumulate(), inner_product() numeric
back_inserter() iterator
equal_to(), less(), bind2nd() functional
set_new_handler() new
C Library Functions Header
atoi(), atof(), abs(), rand(), system(), exit() cstdlib
isalpha(), isdigit(), tolower(), toupper() cctype
sqrt(), log(), exp(), pow(), sin(), cos(), atan() cmath
clock(), time() ctime
strlen(), memset(), memmove(), memcmp() cstring
printf(), fopen(), getc(), perror() cstdio
assert() cassert
C++ allows you to create your own types and libraries. The most important type is a class, allowing object oriented programming. A class is an abstract data type with a hidden representation and a set of public member functions and types. Classes can be organized into a hierarchy (inheritance), and you can write code that accepts any type in this hierarchy (polymorphism). Functions and classes can be parameterized by type (templated).
class T {...}; Defines T as a collection of types, objects, and member functions
template <class T> ... Defines a set of functions or classes over all T
typedef T U; Defines type U is a synonym for T
enum T {...}; Defines T as an int, and set of int constants
struct T {...}; Like a class, except default scope of members is public
union T {...}; A struct with object members overlapping in memory
namespace N {...}; Defines a scope for a collection of types, objects, and functions
Program Organization (compiling, linking, make)
History of C++
Further Reading
Basics
C++ is a compiled language, an upward compatible superset of C and an (incompatible) predecessor to Java. C++ compiles C programs but adds object oriented (OO) features (classes, inheritance, polymorphism), templates (generic functions and classes), function and operator overloading, namespaces (packages), exception handling, a library of standard data structures (string, vector, map, etc.) and formatted text I/O (istream, ostream). Unlike Java, C++ lacks a standard graphical user interface (GUI), network interface, garbage collection, and threads, and allows non-OO programming and unchecked low-level machine operations with pointers. However, C++ executes faster than Java and requires no run-time support.
A C++ program is a collection of function, object, and type declarations. Every program must have a function int main() { ... } where the curly braces enclose a block, a sequence of declarations and statements ending in semicolons which are executed in order. A statement is an expression, block, or control statement that alters the order of execution, such as if, while, for, break, return. Some types (std::string), objects (std::cout), and functions are defined in header files, requiring the line #include <header> before use. Items defined in the standard headers are in the namespace std. The std:: prefix may be dropped after the statementusing namespace std;. For instance,
// Comment: prints "Hello world!" and an OS-independent newline
#include <string> // Defines type std::string
#include <iostream> // Defines global object std::cout
using namespace std; // Allow std:: to be dropped
int main() { // Execution starts here
string s="Hello world!\n"; // Declares object s of type string
cout << s; // An expression as a statement, << is the output operator
return 0; // Execution ends here
}
The symbol // denotes a comment to the end of the line. You may also use /* ... */ for multiline comments. Spacing and indentation is used for readability. C++ is mostly free-form, except that the end of line is significant after # and //. C++ is case sensitive.
C++ source code files should be created with a text editor and have the extension .cpp. If the above is called hello.cpp, it may be compiled and run as follows in a UNIX shell window:
g++ hello.cpp -o hello -Wall -O
./hello
The -o option renames the executable file, by default a.out. -Wall turns on all warnings (recommended). -O optimizes (compiles slower but runs faster).
In Windows, the GNU C++ compiler is called DJGPP. To compile and run from an MS-DOS box:
gxx hello.cpp -o hello.exe
hello
The output file must have a .EXE extension (default is A.EXE). There is also a .OBJ file which you can delete.
To use the network or GUI interface in UNIX, you must use the X and socket libraries, which don't work in Windows. In Windows, you must use the Windows API and a compiler that supports them, such as from Microsoft, Borland, or Symantec. GUI/network programming is nonportable and outside the scope of this document.
Links to free and commercial C++ compilers can be found at cplusplus.com.
Statements
A program consists of a collection of functions (one of which must be int main() {...}) and type and object declarations. A function may contain declarations and statements. Statements have the following forms, where s is a statement, and t is a true/false expression.
s; // Expression or declaration
; // Empty statement
{s; s;} // A block of 0 or more statements is a statement
if (t) s; // If t is true then s
if (t) s; else s; // else is optional
while (t) s; // Loop 0 or more times
for (s1; t; s2) s; // s1; while (t) {s; s2;}
break; // Jump from while, for, do, switch
return x; // Return x to calling function
try {throw x;} // Throw exception, abort if not caught, x has any type
catch (T y) {s;} // if x has type T then y=x, jump to s
catch (...) {s;} // else jump here (optional)
do s; while (t); // (uncommon) s; while (t) s;
continue; // (uncommon) Start next loop of while, for, do
switch (i) { // (uncommon) Test int expression i to const C
case C: s; break; // if (i==C) go here
default: s; // optional, else go here
}
label: goto label; // (rare) Jump to label within a function
A statement may be a declaration or an expression. Objects and types declared in a block are local to that block. (Functions cannot be defined locally). It is normal (but not required) to show statements on separate lines and to indent statements enclosed in a block. If braces are optional, we indent anyway. For instance,
{ // start of block
int a[10], i=0, j; // declaration
a[i+2]=3; // expression
} // end of block, a, i, and j are destroyed
declares the array of int a with elements a[0] through a[9] (whose values are initially undefined), i with initial value 0, and j with an undefined initial value. These names can only be used in scope, which is from the declaration to the closing brace.
The for loop is normally used for iteration. For instance, the following both exit the loop with i set to the index of the first element of a such that a[i] is 0, or to 10 if not found.
for (i=0; i<10; i=i+1) { i=0;
if (a[i]==0) { while (i<10) {
break; if (a[i]==0)
} break;
} i=i+1;
}
The braces in the for loop are optional because they each enclose a single statement. In the while loop, the outer braces are required because they enclose 2 statements. All statements are optional: for (;;) loops forever. The first statement in a for loop may declare a variable local to the loop.
for (int i=0; i<10; i=i+1)
It is only possible to break from the innermost loop of a nested loop. continue in a for loop skips the rest of the block but executes the iteration (s2) and test before starting the next loop.
int sum(int x, int y) { // Function definition
return x+y;
}
int main() {
int a=sum(1,2); // a=3;
return 0; // By convention, nonzero indicates an error
}
A test of several alternatives usually has the form if (t) s; else if (t) s; else if (t) s; ... else s;. A switch statement is an optimization for the special case where an int expression is tested against a small range of constant values. The following are equivalent:
switch (i) { if (i==1)
case 1: j=1; break; j=1;
case 2: // fall thru else if (i==2 || i==3) // || means "or else"
case 3: j=23; break; j=23;
default: j=0; else
} j=0;
throw x jumps to the first catch statement of the most recently executed try block where the parameter declaration matches the type of x, or a type that x can be converted to, or is .... At most one catch block is executed. If no matching catch block is found, the program aborts (Unexpected exception). throw; with no expression in a catch block throws the exception just caught. Exceptions are generally used when it is inconvenient to detect and handle an error in the same place.
void f() {
throw 3;
}
int main() {
try {
f();
}
catch(int i) { // Execute this block with i = 3
throw; // throw 3 (not caught, so program aborts)
}
catch(...) { // Catch any other type
}
}
Expressions
There are 18 levels of operator precedence, listed highest to lowest. Operators at the same level are evaluated left to right unless indicted, Thus, a=b+c means a=(b+c) because + is higher than =, and a-b-c means (a-b)-c. Order of evaluation is undefined, e.g. for sin(x)+cos(x) we cannot say whether sin() or cos() is called first.
The meaning of an expression depends on the types of the operands. (x,y) denotes a comma separated list of 0 or more objects, e.g. (), (x), or (1,2,3,4).
1
X::m Member m of namespace or class X
::m Global name m when otherwise hidden by a local declaration
2
p[i] i'th element of container p (array, vector, string)
x.m Member m of object x
p->m Member m of object pointed to by p
f(x,y) Call function f with 0 or more arguments
i++ Add 1 to i, result is original value of i
i-- Subtract 1 from i, result is original value of i
static_cast<T>(x) Convert x to type T using defined conversions
const_cast<T>(x) (rare) Convert x to equivalent but non-const T
reinterpret_cast<T>(x) (rare, dangerous) Pretend x has type T
dynamic_cast<T>(x) (rare) Convert base pointer or reference to derived if possible
typeid(x) (rare) If x is type T, then typeid(x)==typeid(T) (in <typeinfo>)
3 (right to left)
*p Contents of pointer p, or p[0]. If p is type T*, *p is T
&x Address of (pointer to) x. If x is type T, &x is T*
-a Negative of numeric a
!i Not i, true if i is false or 0
~i Bitwise compliment of i, -1 - i
(T)x Convert (cast) object x to type T (by static, const, or reinterpret)
T(x,y) Convert, initializing with 0 or more arguments
new T Create a T object on heap, return its address as T*
new T(x,y) Create, initializing with 0 or more arguments
new(p) T (rare) Initialize T at address p without allocating from heap
new(p) T(x,y) (rare) Initialize T with 0 or more arguments at p
new T[i] Create array of i objects of type T, return T* pointing to first element
delete p Destroy object pointed to by p obtained with new T or new T()
delete[] p Destroy array obtained with new T[]
++i Add 1 to i, result is the new i
--i Subtract 1 from i, result is the new i
sizeof x Size of object x in bytes
sizeof(T) Size of objects of type T in bytes
4
x.*p (rare) Object in x pointed to by pointer to member p
q->*p (rare) Object in *q pointed to by pointer to member p
5
a*b Multiply numeric a and b
a/b Divide numeric a and b, round toward 0 if both are integer
i%j Integer remainder i-(i/j)*j
6
a+b Addition, string concatenation
a-b Subtraction
7
x<<y Integer x shifted y bits to left, or output y to ostream x
x>>y Integer x shifted y bits to right, or input y from istream x
8
x<y Less than
x>y Greater than
x<=y Less than or equal to
x>=y Greater than or equal to
9
x==y Equals
x!=y Not equals
10
i&j Bitwise AND of integers i and j
11
i^j Bitwise XOR of integers i and j
12
i|j Bitwise OR of integers i and j
13
i&&j i and then j (evaluate j only if i is true/nonzero)
14
i||j i or else j (evaluate j only if i is false/zero)
15 (right to left)
x=y Assign y to x, result is new value of x
x+=y x=x+y, also -= *= /= %= &= |= ^= <<= >>=
16
i?x:y If i is true/nonzero then x else y
17
throw x Throw exception x (any type)
18
x,y Evaluate x and y (any types), result is y
Expressions that don't require creating a new object, such as a=b, ++a, p[i], p->m, x.m, a?b:c, a,b etc. are lvalues, meaning they may appear on the left side of an assignment. Other expressions and conversions create temporary objects to hold the result, which are const (constant). An expression used as a statement discards the final result.
int a, b, c;
a+b; // Legal, add a and b, discard the sum
a=b=c; // Legal, assign c to b, then assign the new b to a
(a+=b)+=c; // Legal, add b to a, then add c to a
a+b=c; // Error, a+b is const
double(a)=b; // Error, double(a) is const
double d; d=static_cast<double>(3); // Explicit 3 to 3.0
d=3; // Implicit conversion
d=sqrt(3); // Implicit 3.0, sqrt() expects double
vector<int> v(5); // This constructor is explicit
v=5; // Error, no implicit conversion
v=static_cast<vector<int> >(5); // OK
const_cast<T>(x) allows an object to be modified through a const pointer or reference. It must always be explicit.
int x=3;
const int& r=x; r=4; // Error, r is const
const_cast<int&>(r)=4; // OK, x=4
const int* p=&x; *p=5; // Error, *p is const
*const_cast<int*>(p)=5; // OK, x=5
If x were const, then this code would still be allowed but it is undefined whether x actually changes.
reinterpret_cast<T>(x) turns off normal type checking between int and different pointer types, which are normally incompatible. The only safe conversion is to convert a pointer back to its original type. Conversion is always explicit.
int x=3, *p=&x; *p=5; // OK, x=5
*reinterpret_cast<double*>(p)=5; // Crash, writing 8 bytes into 4
The expression (T)x applies whatever combination of static, const, and reinterpret casts are needed to convert x to type T. T(x) is a static_cast.
const char* s="hello";
int(*s); // static_cast
(char*)s; // const_cast
(const int*)s; // reinterpret_cast
(int*)s; // reinterpret_cast and const_cast
Declarations
A declaration creates a type, object, or function and gives it a name. The syntax is a type name followed by a list of objects with possible modifiers and initializers applying to each object. A name consists of upper or lowercase letters, digits, and underscores (_) with a leading letter. (Leading underscores are allowed but may be reserved). An initializer appends the form =x where x is an expression, or (x,y) for a list of one or more expressions. For instance,
string s1, s2="xxx", s3("xxx"), s4(3,'x'), *p, a[5], next_Word();
declares s1 to be a string with initial value "", s2, s3, and s4 to be strings with initial value "xxx", p to be a pointer to string, a to be an array of 5 strings (a[0] to a[4] with initial values ""), and next_Word to be a function that takes no parameters and returns a string.
Built-in Types
All built-in types are numeric. They are not automatically initialized to 0 unless global or static.
int a, b=0; // a's value is undefined
static double x; // 0.0
Types and their usual ranges are listed below. Actual ranges could be different. The most important types are int, bool, char, and double.
Integer types
How to Program in C++
You may copy this file for noncommercial use. The latest version is located at cs.fit.edu/~mmahoney/cse2050/how2cpp.html updated Apr. 14, 2010. Please report errors to Matt Mahoney at [email protected]. Seldom-used features have been deliberately omitted.
Language Summary
Statements if, for, while, return, break...
Expressions arithmetic, comparison, assignment...
The most important types are int, char, bool, double, and the containers string, vector, and map. Summary of common types:
Built-in Description
int x; Fastest integer type (16-32 bits), also short, long, unsigned
char x; 8-bit character, '\0' to '\xFF' or -128 to 127
double x; 64 bit real + or - 1.8e308, 14 significant digits, also float
bool x; true or false
Modifiers Description
const T x; Non-modifiable object
T& y=x; Reference, y is an alias for x, which both have type T
T f(...) {...} Defines f as a function returning T
T* p; Pointer to T (*p is a T object)
T a[N]; Array of N elements of T, a[0] to a[N-1]
static T x; Place x in data segment
register T x; (rare) Hint to optimize for speed
volatile T x; (rare) x may be modified externally
The following standard library types and functions require at the beginning of the program:
#include <header>
using namespace std;
Library Type Description Header
istream Standard input (cin) iostream
ostream Output (cout, cerr, clog) iostream
ifstream Input file fstream
ofstream Output file fstream
string Sequence of char string
vector<T> Expandable array/stack of T vector
deque<T> Array/double ended queue deque
list<T> List/stack/queue of T list
map<T1,T2> Associative mapping of T1 to T2 map
set<T1> A map with keys only set
pair<T1,T2> Two objects of type T1 and T2 map or utility
priority_queue<T> Sorted queue queue
stack<T> Stack stack
bitset<N> Array of N bool with logical operations bitset
valarray<T> Array with arithmetic operations valarray
complex<T> Complex number complex
iterator Pointer into a container (Included with container)
const_iterator Pointer not allowing element assignment (Included with container)
exception Hierarchy of exception types stdexcept, exception
C++ Standard Library Functions Header
min(), max(), swap(), sort(), copy(), equal() algorithm
accumulate(), inner_product() numeric
back_inserter() iterator
equal_to(), less(), bind2nd() functional
set_new_handler() new
C Library Functions Header
atoi(), atof(), abs(), rand(), system(), exit() cstdlib
isalpha(), isdigit(), tolower(), toupper() cctype
sqrt(), log(), exp(), pow(), sin(), cos(), atan() cmath
clock(), time() ctime
strlen(), memset(), memmove(), memcmp() cstring
printf(), fopen(), getc(), perror() cstdio
assert() cassert
C++ allows you to create your own types and libraries. The most important type is a class, allowing object oriented programming. A class is an abstract data type with a hidden representation and a set of public member functions and types. Classes can be organized into a hierarchy (inheritance), and you can write code that accepts any type in this hierarchy (polymorphism). Functions and classes can be parameterized by type (templated).
class T {...}; Defines T as a collection of types, objects, and member functions
template <class T> ... Defines a set of functions or classes over all T
typedef T U; Defines type U is a synonym for T
enum T {...}; Defines T as an int, and set of int constants
struct T {...}; Like a class, except default scope of members is public
union T {...}; A struct with object members overlapping in memory
namespace N {...}; Defines a scope for a collection of types, objects, and functions
Program Organization (compiling, linking, make)
History of C++
Further Reading
Basics
C++ is a compiled language, an upward compatible superset of C and an (incompatible) predecessor to Java. C++ compiles C programs but adds object oriented (OO) features (classes, inheritance, polymorphism), templates (generic functions and classes), function and operator overloading, namespaces (packages), exception handling, a library of standard data structures (string, vector, map, etc.) and formatted text I/O (istream, ostream). Unlike Java, C++ lacks a standard graphical user interface (GUI), network interface, garbage collection, and threads, and allows non-OO programming and unchecked low-level machine operations with pointers. However, C++ executes faster than Java and requires no run-time support.
A C++ program is a collection of function, object, and type declarations. Every program must have a function int main() { ... } where the curly braces enclose a block, a sequence of declarations and statements ending in semicolons which are executed in order. A statement is an expression, block, or control statement that alters the order of execution, such as if, while, for, break, return. Some types (std::string), objects (std::cout), and functions are defined in header files, requiring the line #include <header> before use. Items defined in the standard headers are in the namespace std. The std:: prefix may be dropped after the statementusing namespace std;. For instance,
// Comment: prints "Hello world!" and an OS-independent newline
#include <string> // Defines type std::string
#include <iostream> // Defines global object std::cout
using namespace std; // Allow std:: to be dropped
int main() { // Execution starts here
string s="Hello world!\n"; // Declares object s of type string
cout << s; // An expression as a statement, << is the output operator
return 0; // Execution ends here
}
The symbol // denotes a comment to the end of the line. You may also use /* ... */ for multiline comments. Spacing and indentation is used for readability. C++ is mostly free-form, except that the end of line is significant after # and //. C++ is case sensitive.
C++ source code files should be created with a text editor and have the extension .cpp. If the above is called hello.cpp, it may be compiled and run as follows in a UNIX shell window:
g++ hello.cpp -o hello -Wall -O
./hello
The -o option renames the executable file, by default a.out. -Wall turns on all warnings (recommended). -O optimizes (compiles slower but runs faster).
In Windows, the GNU C++ compiler is called DJGPP. To compile and run from an MS-DOS box:
gxx hello.cpp -o hello.exe
hello
The output file must have a .EXE extension (default is A.EXE). There is also a .OBJ file which you can delete.
To use the network or GUI interface in UNIX, you must use the X and socket libraries, which don't work in Windows. In Windows, you must use the Windows API and a compiler that supports them, such as from Microsoft, Borland, or Symantec. GUI/network programming is nonportable and outside the scope of this document.
Links to free and commercial C++ compilers can be found at cplusplus.com.
Statements
A program consists of a collection of functions (one of which must be int main() {...}) and type and object declarations. A function may contain declarations and statements. Statements have the following forms, where s is a statement, and t is a true/false expression.
s; // Expression or declaration
; // Empty statement
{s; s;} // A block of 0 or more statements is a statement
if (t) s; // If t is true then s
if (t) s; else s; // else is optional
while (t) s; // Loop 0 or more times
for (s1; t; s2) s; // s1; while (t) {s; s2;}
break; // Jump from while, for, do, switch
return x; // Return x to calling function
try {throw x;} // Throw exception, abort if not caught, x has any type
catch (T y) {s;} // if x has type T then y=x, jump to s
catch (...) {s;} // else jump here (optional)
do s; while (t); // (uncommon) s; while (t) s;
continue; // (uncommon) Start next loop of while, for, do
switch (i) { // (uncommon) Test int expression i to const C
case C: s; break; // if (i==C) go here
default: s; // optional, else go here
}
label: goto label; // (rare) Jump to label within a function
A statement may be a declaration or an expression. Objects and types declared in a block are local to that block. (Functions cannot be defined locally). It is normal (but not required) to show statements on separate lines and to indent statements enclosed in a block. If braces are optional, we indent anyway. For instance,
{ // start of block
int a[10], i=0, j; // declaration
a[i+2]=3; // expression
} // end of block, a, i, and j are destroyed
declares the array of int a with elements a[0] through a[9] (whose values are initially undefined), i with initial value 0, and j with an undefined initial value. These names can only be used in scope, which is from the declaration to the closing brace.
The for loop is normally used for iteration. For instance, the following both exit the loop with i set to the index of the first element of a such that a[i] is 0, or to 10 if not found.
for (i=0; i<10; i=i+1) { i=0; if (a[i]==0) { while (i<10) { break; if (a[i]==0) } break; } i=i+1; }The braces in the for loop are optional because they each enclose a single statement. In the while loop, the outer braces are required because they enclose 2 statements. All statements are optional: for (;;) loops forever. The first statement in a for loop may declare a variable local to the loop.
for (int i=0; i<10; i=i+1)
It is only possible to break from the innermost loop of a nested loop. continue in a for loop skips the rest of the block but executes the iteration (s2) and test before starting the next loop.
int sum(int x, int y) { // Function definition return x+y; } int main() { int a=sum(1,2); // a=3; return 0; // By convention, nonzero indicates an error }
A test of several alternatives usually has the form if (t) s; else if (t) s; else if (t) s; ... else s;. A switch statement is an optimization for the special case where an int expression is tested against a small range of constant values. The following are equivalent:
switch (i) { if (i==1)
case 1: j=1; break; j=1;
case 2: // fall thru else if (i==2 || i==3) // || means "or else"
case 3: j=23; break; j=23;
default: j=0; else
} j=0;
throw x jumps to the first catch statement of the most recently executed try block where the parameter declaration matches the type of x, or a type that x can be converted to, or is .... At most one catch block is executed. If no matching catch block is found, the program aborts (Unexpected exception). throw; with no expression in a catch block throws the exception just caught. Exceptions are generally used when it is inconvenient to detect and handle an error in the same place.
void f() {
throw 3;
}
int main() {
try {
f();
}
catch(int i) { // Execute this block with i = 3
throw; // throw 3 (not caught, so program aborts)
}
catch(...) { // Catch any other type
}
}
Expressions
There are 18 levels of operator precedence, listed highest to lowest. Operators at the same level are evaluated left to right unless indicted, Thus, a=b+c means a=(b+c) because + is higher than =, and a-b-c means (a-b)-c. Order of evaluation is undefined, e.g. for sin(x)+cos(x) we cannot say whether sin() or cos() is called first.
The meaning of an expression depends on the types of the operands. (x,y) denotes a comma separated list of 0 or more objects, e.g. (), (x), or (1,2,3,4).
1
X::m Member m of namespace or class X
::m Global name m when otherwise hidden by a local declaration
2
p[i] i'th element of container p (array, vector, string)
x.m Member m of object x
p->m Member m of object pointed to by p
f(x,y) Call function f with 0 or more arguments
i++ Add 1 to i, result is original value of i
i-- Subtract 1 from i, result is original value of i
static_cast<T>(x) Convert x to type T using defined conversions
const_cast<T>(x) (rare) Convert x to equivalent but non-const T
reinterpret_cast<T>(x) (rare, dangerous) Pretend x has type T
dynamic_cast<T>(x) (rare) Convert base pointer or reference to derived if possible
typeid(x) (rare) If x is type T, then typeid(x)==typeid(T) (in <typeinfo>)
3 (right to left)
*p Contents of pointer p, or p[0]. If p is type T*, *p is T
&x Address of (pointer to) x. If x is type T, &x is T*
-a Negative of numeric a
!i Not i, true if i is false or 0
~i Bitwise compliment of i, -1 - i
(T)x Convert (cast) object x to type T (by static, const, or reinterpret)
T(x,y) Convert, initializing with 0 or more arguments
new T Create a T object on heap, return its address as T*
new T(x,y) Create, initializing with 0 or more arguments
new(p) T (rare) Initialize T at address p without allocating from heap
new(p) T(x,y) (rare) Initialize T with 0 or more arguments at p
new T[i] Create array of i objects of type T, return T* pointing to first element
delete p Destroy object pointed to by p obtained with new T or new T()
delete[] p Destroy array obtained with new T[]
++i Add 1 to i, result is the new i
--i Subtract 1 from i, result is the new i
sizeof x Size of object x in bytes
sizeof(T) Size of objects of type T in bytes
4
x.*p (rare) Object in x pointed to by pointer to member p
q->*p (rare) Object in *q pointed to by pointer to member p
5
a*b Multiply numeric a and b
a/b Divide numeric a and b, round toward 0 if both are integer
i%j Integer remainder i-(i/j)*j
6
a+b Addition, string concatenation
a-b Subtraction
7
x<<y Integer x shifted y bits to left, or output y to ostream x
x>>y Integer x shifted y bits to right, or input y from istream x
8
x<y Less than
x>y Greater than
x<=y Less than or equal to
x>=y Greater than or equal to
9
x==y Equals
x!=y Not equals
10
i&j Bitwise AND of integers i and j
11
i^j Bitwise XOR of integers i and j
12
i|j Bitwise OR of integers i and j
13
i&&j i and then j (evaluate j only if i is true/nonzero)
14
i||j i or else j (evaluate j only if i is false/zero)
15 (right to left)
x=y Assign y to x, result is new value of x
x+=y x=x+y, also -= *= /= %= &= |= ^= <<= >>=
16
i?x:y If i is true/nonzero then x else y
17
throw x Throw exception x (any type)
18
x,y Evaluate x and y (any types), result is y
Expressions that don't require creating a new object, such as a=b, ++a, p[i], p->m, x.m, a?b:c, a,b etc. are lvalues, meaning they may appear on the left side of an assignment. Other expressions and conversions create temporary objects to hold the result, which are const (constant). An expression used as a statement discards the final result.
int a, b, c;
a+b; // Legal, add a and b, discard the sum
a=b=c; // Legal, assign c to b, then assign the new b to a
(a+=b)+=c; // Legal, add b to a, then add c to a
a+b=c; // Error, a+b is const
double(a)=b; // Error, double(a) is const
double d; d=static_cast<double>(3); // Explicit 3 to 3.0 d=3; // Implicit conversion d=sqrt(3); // Implicit 3.0, sqrt() expects double vector<int> v(5); // This constructor is explicit v=5; // Error, no implicit conversion v=static_cast<vector<int> >(5); // OK
const_cast<T>(x) allows an object to be modified through a const pointer or reference. It must always be explicit.
int x=3; const int& r=x; r=4; // Error, r is const const_cast<int&>(r)=4; // OK, x=4 const int* p=&x; *p=5; // Error, *p is const *const_cast<int*>(p)=5; // OK, x=5If x were const, then this code would still be allowed but it is undefined whether x actually changes.
reinterpret_cast<T>(x) turns off normal type checking between int and different pointer types, which are normally incompatible. The only safe conversion is to convert a pointer back to its original type. Conversion is always explicit.
int x=3, *p=&x; *p=5; // OK, x=5 *reinterpret_cast<double*>(p)=5; // Crash, writing 8 bytes into 4The expression (T)x applies whatever combination of static, const, and reinterpret casts are needed to convert x to type T. T(x) is a static_cast.
const char* s="hello";
int(*s); // static_cast
(char*)s; // const_cast
(const int*)s; // reinterpret_cast
(int*)s; // reinterpret_cast and const_cast
Declarations
A declaration creates a type, object, or function and gives it a name. The syntax is a type name followed by a list of objects with possible modifiers and initializers applying to each object. A name consists of upper or lowercase letters, digits, and underscores (_) with a leading letter. (Leading underscores are allowed but may be reserved). An initializer appends the form =x where x is an expression, or (x,y) for a list of one or more expressions. For instance,
string s1, s2="xxx", s3("xxx"), s4(3,'x'), *p, a[5], next_Word();
declares s1 to be a string with initial value "", s2, s3, and s4 to be strings with initial value "xxx", p to be a pointer to string, a to be an array of 5 strings (a[0] to a[4] with initial values ""), and next_Word to be a function that takes no parameters and returns a string.
Built-in Types
All built-in types are numeric. They are not automatically initialized to 0 unless global or static. int a, b=0; // a's value is undefined
static double x; // 0.0
Types and their usual ranges are listed below. Actual ranges could be different. The most important types are int, bool, char, and double.
Integer types