// /* // // // // // // // // // Comment to end of line Multi-line comment */ Insert standard header file Insert file in current directory Replace X with some text Replace F(1,2) with 1+2 Line continuation Remove definition Condional compilation (#ifdef X) Optional (#ifndef X or #if !defined(X)) Required after #if, #ifdef

const int c=3; to const int* p=a; int* const p=a; const int* const p=a; const int& cr=x;

// Constants must be initialized, cannot assign // // // // Contents of p (elements of a) are constant p (but not contents) are constant Both p and its contents are constant cr cannot be assigned to change x

int x; static int x; extern int x; // Auto (memory exists only while in scope) // Global lifetime even if local scope // Information only, declared elsewhere

#include <stdio.h> #include "myfile.h" #define X some text #define F(a,b) a+b #define X \ some text #undef X #if defined(X) #else #endif

x=y; int x; ; { int x; block a; } if (x) a; else if (y) b; else c; while (x) a; for (x; y; z) a; do a; while (x); // Every expression is a statement // Declarations are statements // Empty statement // A block is a single statement // Scope of x is from declaration to end of // In C, declarations must precede statements // If x is true (not 0), evaluate a // If not x and y (optional, may be repeated) // If not x and not y (optional) // Repeat 0 or more times while x is true // Equivalent to: x; while(y) {a; z;} // Equivalent to: a; while(x) a; // // // // x must be int If x == X1 (must be a const), jump here Else if x == X2, jump here Else jump here (optional)


255, 0377, 0xff 2147483647L, 0x7fffffffl 123.0, 1.23e2 'a', '\141', '\x61' '\n', '\\', '\'', '\"' quote "string\n" \0 "hello" "world" true, false

// // // // //

Integers (decimal, octal, hex) Long (32-bit) integers double (real) numbers Character (literal, octal, hex) Newline, backslash, single quote, double

// Array of characters ending with newline and // Concatenated strings // bool constants 1 and 0

int x; // Declare x to be an integer (value undefined) int x=255; // Declare and initialize x to 255 short s; long l; // Usually 16 or 32 bit integer (int may be either) char c='a'; // Usually 8 bit character unsigned char u=255; signed char s=-1; // char might be either unsigned long x=0xffffffffL; // short, int, long are signed float f; double d; // Single or double precision real (never unsigned) bool b=true; // true or false, may also use int (1 or 0) int a, b, c; // Multiple declarations int a[10]; // Array of 10 ints (a[0] through a[9]) int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; ) int a[2][3]={{1,2,3},{4,5,6}}; // Array of array of ints char s[]="hello"; // String (6 elements including '\0') int* p; // p is a pointer to (address of) int char* s="hello"; // s points to unnamed array containing "hello" void* p=NULL; // Address of untyped memory (NULL is 0) int& r=x; // r is a reference to (alias of) int x enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN enum weekend day; // day is a variable of type weekend enum weekend {SAT=0,SUN=1}; // Explicit representation as int enum {SAT,SUN} day; // Anonymous enum typedef String char*; // String s; means char* s; switch (x) { case X1: a; case X2: b; default: c; } break; continue; return x; try { a; } catch (T t) { b; } catch (...) { c; }

// Jump out of while, do, or for loop, or switch // Jump to bottom of while, do, or for loop // Return x from function to caller // If a throws a T, then jump here // If a throws something else, jump here

int f(int x, int); int void f(); void f(int a=0); f(); inline f(); f() { statements; } T operator+(T x, T y); T operator-(T x); T operator++(int); extern "C" {void f();} // f is a function taking 2 ints and returning // // // // // // // // // f is a procedure taking no arguments f() is equivalent to f(0) Default return type is int Optimize for speed Function definition (must be global) a+b (if type T) calls operator+(a, b) -a calls function operator-(a) postfix ++ or -- (parameter ignored) f() was compiled in C

one of which must be: int main() { statements. checked at run time // Converts x to a T. } or int main(int argc. x << y x >> y x x x x < y <= y > y >= y // x shifted y bits to left (x * pow(2. } // Assignment operator ~T(). aborts if not caught // evaluates x and y. // Member data void f(). returns y (seldom used) EXPRESSIONS x | y x && y Operators are grouped by precedence. All others are left to right. use . y // Address of allocated n-element array of T // Destroy and free object at address p // Destroy and free array of objects at p // Convert x to T (obsolete. invalid pointers.y // Member x of struct or class t // Member x of struct or class pointed to by p // i'th element of array a // Call to function f with arguments x and y // Object of class T initialized with x and y // Add 1 to x. evaluates to new value // Bitwise complement of x // true if x is 0. else false (1 or 0 in C) // Unary minus // Unary plus (default) // Address of x // Contents of address p (*&x equals x) // Address of newly allocated T object // Address of a T initialized with x. // Shared code.operator-() T(): x(1) {} // Constructor with initialization list T(const T& t): x(t.} // Inline member function void h() const. T::X // Name X defined in class T N::X // Name X defined in namespace N ::X // Global name X t. 1 or higher for errors. New operators may not be created..x) {} // Copy constructor T& operator=(const T& t) {x=t. not checked // Interpret bits of x as a T // Converts x to same type T but not const // Number of bytes used to represent object x // Number of bytes to represent type T // Add 1 to x. returns new value of x // x = x + y.. or &x[y] // Subtract. evaluates to original x // Type of x // Equals typeid(x) if x is a T // Converts x to a T. y)) // x shifted y bits to right (x / pow(2. // -t means t.* ?: may be overloaded. y CLASSES class T { // A new type private: // Section accessible only to T's member functions protected: // Also accessable to classes derived from T public: // Accessable to all int x. There are no run time checks for arrays out of bounds.. // t+y means t. else z // Throw exception. // Does not modify any data members int operator+(int y). etc. Functions with different parameters may have the same name (overloading). // Allow t=T(3) but not t=3 operator int() const {return x. y)) // // // // Less than Less than or equal to Greater than Greater than or equal to x == y x != y x & y x ^ y // Equals // Not equals // Bitwise and (3 & 6 is 2) // Bitwise exclusive or (3 ^ 6 is 5) // Bitwise or (3 | 6 is 7) // x and then y (evaluates y only if x (not 0)) // x or else y (evaluates y only if x is false // Assign y to x. also -= *= /= <<= >>= &= |= ^= // y if x is true (nonzero). Precedence does not affect order of evaluation.. Unary operators and assignment evaluate right to left.Function parameters and return values may be of any type. // Global function i() has private access friend class U.operator+(y) int operator-()._cast<T>(x)) // Multiply // Divide (integers round toward 0) // Modulo (result has sign of x) // Add. y) new T[x] delete p delete[] p (T) x x * y x / y x % y x + y x . or number of elements from *x to *y x || y (0)) x = y x += y x ? y : z throw x x . // Call to static member . . Operators except :: .y) x++ x-typeid(x) typeid(T) dynamic_cast<T>(x) static_cast<T>(x) reinterpret_cast<T>(x) const_cast<T>(x) sizeof x sizeof(T) ++x --x ~x !x -x +x &x *p new T new T(x.) int T::y = 2.} // Allows int(t) friend void i(). // Destructor (automatic cleanup routine) explicit T(int a). By convention. // Member function void g() {return. A function must either be declared or defined before it is used. May access y but not x class Z {}.x p->x a[i] f(x. // Initialization of static member (required) T::l(). // T::V means int }. evaluates to new value (prefix) // Subtract 1 from x.y) T(x. } argv is an array of argc strings from the command line. return *this. void T::f() { // Code for member function f of class T this->x = x. which is undefined. Every program consists of a set of a set of global variable declarations and a set of function definitions (possibly in separate files)..x. main returns status 0 if successful. // Data shared by all T objects static void l(). highest first. // Nested class T::Z typedef int V. // Members of class U have private access static int y. It may be declared first and defined later. Precedence order is not affected.} // this is address of self (means x=x. evaluates to original x (postfix) // Subtract 1 from x. char* argv[]) { statements.

public class X: public virtual T directly // Equivalent to: class T { public: // May be overridden at run time by derived // Must be overridden (pure virtual) // Derived class U inherits all members of base // Inherited members of T become private U {}.H. -1L if error fseek(f. and destructor. return 0 if OK Create temporary file in mode "wb+" Put a unique file name in char s[L_tmpnam] STDLIB. f = tmpfile(). assignment operator. int Random int 0 to RAND_MAX. File names are actually lower case.H. // Open for reading. f) putchar(c). NULL if EOF fgets(s. template <class parameters T> T f(T t). fprintf(stderr. tan(x). STDIO. CCTYPE (Character types) isalnum(c).// rand().h are in namespace std. return 0 if OK Rename file. c. long left just. // void* p = malloc(n). long hex // float or double: 123. There is also a default noargument constructor (required to create arrays) if the class has no constructors.. // Copy n bytes from src to dst memcmp(s1. isalpha(c). // Copy up to n chars. return number Force buffered writes to f Position binary file f at n Position in f. INT_MAX. // Compare n bytes as in strcmp memchr(s. long NAMESPACES namespace N {class T {}. SEEK_SET). "x=%d". HEX. strcpy(dst. rename("old". also strncat().000000. rewind(f). src.c). n).. // Trig functions. src). int n=0> Overload f for all types Class with type parameter T A constructor Definition of constructor An object of type "X of int" // Template with default putc(c. <0 if s1<s2. written fflush(f). // Find first byte c in s. atoi(s). NULL (0) if error (write) "a" append.} // Hide name T N::T t.. SEEK_SET). // Address of first substring in s or 0 // mem. Header files without . "a+" update. // // // // Is c a letter or digit? Is c a letter? Digit? Is c lower case? Upper case? Convert c to lower/upper case MATH. f).// Address of first/last char c in s or 0 strstr(s. assignment. n.23e2. isupper(c). functions) atof(s). "new"). Obsolete: use new Free memory. which perform the corresponding operations on each data member and each base class as shown above. stdout). 1. TEMPLATES template <class template <class X(T t). cos(x). // Make T visible without N:: STRING. putc(c. s2). ferror(f). n). 123. fprintf(f. T class V: private T {}. class virtual void g()=0. Constructors.1f" "%e %g" "%c %s" "%%" sprintf(s. labs(ln). no bounds check Read n bytes from f to s. "rb" binary // Close file f // Print "x=3" Other conversions: // int width 5. islower(c). CTYPE. n. length n bytes memmove(dst.H. s2. fwrite(s. n). remove("filename"). f). printf("x=%d”. and destructors do not inherit. tmpnam(s). class W: public T. // Use name T in namespace N using namespace N. // Compare. // abs(n).c). char* // % // Print to array of char s // Print to stdout (screen unless redirected) // Print to standard error (not redirected) // Read one char (as an int) or EOF from f // Put back one c to f // getc(stdin). src). unsigned int. // Classes derived from X have base T All classes have a default copy constructor. 3). "x=%d".0 // 1. >0 if s1>s2 strncpy(dst. clearerr(f). sub). reset rand() Allocate n bytes. getchar().H. // Concatenate to dst. hex. 0 if s1==s2. . fgets(s. // system(s). use either f or g // char. // Convert char* s to float. n. // free(p). x (double) is in radians . f). n). c. // Mode may also be "w" fclose(f). return address or 0 memset(s.H. // Length of s not counting \0 strchr(s. clearerr(f). CSTDLIB (Misc. feof(f). 3). return number read Write n bytes of s to f. ftell(f). Obsolete: use delete Kill program. "r"). n). "%5d %u %-8ld" "%o %x %X %lx" "%f %5. 0L. gets(s) fread(s. 1. Read line into char s[n] from f. CSTDIO (Input/output) FILE* f=fopen("filename". strrchr(s. atol(s).struct T { virtual void f(). functions are for any pointer types (void*). ungetc(c. Not bounds checked strcmp(s1. // octal. "%c". // getenv("PATH"). // Copy string. src. Not bounds checked strcat(dst.. CMATH (Floating point math) sin(x). strncmp() strlen(s). // Multiple inheritance {}. n. tolower(c). Is f at end of file? Error in f? Print char* s and error message Clear error code for f Delete file. class U: public T {}. fseek(f. c). srand(seed). return status n Execute OS command s (system dependent) Environment variable or 0 (system dependent) Absolute value as int. perror(s). }. isdigit(c). // exit(n). long. f). template <class X<int> x(3). class U=T. CSTRING (Character array handling functions) Strings are type char[] with a '\0' in the last element used. toupper(c). 3). }. // Set n bytes of s to c C/C++ STANDARD LIBRARY Only the most commonly used functions are listed. T> class X { // // // T> X<T>::X(T t) {} // // T. f). // // // // // // // // // // // // // // // // // // fprintf(f. getc(f).

print message and abort // (before #include <assert. a[20]=1. s1 += s2 + ' ' + "world".second. // Time in seconds since program started time_t t=time(0). // b is copy of a vector<T> c(n..push_front(x).back()=4. ofstream f2("filename"). y (any type defining <) Exchange values of variables x and y Sort array a[0]. CTIME (Clock) clock()/CLOCKS_PER_SEC. 3 a. log base 10 x to the y.second.first. local time VECTOR (Variable sized array/stack with built in memory allocation) vector<int> a(10).get().get(c). sort(a...} ostream& operator<<(ostream& o.size(). // Crash: not bounds checked a. // a[0]. 5 Concatenation Comparison. y). // "hello" a. yday.H.pop_front().size(). // "Day Mon dd hh:mm:ss yyyy\n" asctime(localtime(&t)). IOSTREAM (Replaces stdio.H. also <. y). // Prints hello.end()). // Like a[20] but throws out_of_range() for (vector<int>::iterator p=a. s1 == "hello world" s1[0].end().. FSTREAM (File I/O works like cin. a[10]=3 a.push_back(3). // Set all elements of a to 0 vector<int> b(a.H. // Increase size to 11.10" . >. // a[10]=4. // 1 FSTREAM.front(). // Map from string to int a["hello"]=3.h>). y). p!=a. // Puts x at a[0]. cosh(x).asin(x). d+10). // fabs(x). shifts toward front IOSTREAM. // Inverses atan(y/x) Hyperbolic e to the x. x=. if (f1) f1 >> x. #define NDEBUG // If e is false. a.. min. NEW (Out of memory handler) set_new_handler(handler). 3). etc. f1. ++p) *p=0.H. f1. s1. if (f2) f2 << x. // Change behavior when out of memory void handler(void) {throw bad_alloc(). // a[0]. ++p) cout << (*p). // c[0]. max(x. a+n). // e is initialized from d ASSERT.. if (cin) // Read words x and y (any type) from stdin // Write line to stdout // Write to stderr and flush // c = getchar(). n).a[n-1] by < Sort vector or deque IOMANIP. hour.H. year (-1900). cout as above) ifstream f1("filename").end(). tanh(x).pop_back(). mday. floor(x).size(). // ceil(x). // 0 if UCT unavailable. acos(x).end()). a. // sinh(x). CASSERT (Debugging aid) assert(e). s1.// atan2(y.first << (*p). atan(x). s2. cin. s1.H. square root Round up or down (as a double) Absolute value. wday.// exp(x). swap(x.. else p->tm_X where X is: sec.begin(). 'h' Substring of size n starting at s1[m] Convert to const char* Read line ending in '\n' TIME.h) cin >> x >> y.1. cin.. // // // // // // // // Create strings Number of characters: 0. a. // 3 MAP (associative array) map<string. fmod(x. sort(a.at(20)=1. getline(cin. but also supports: a. s).size(). c = cin. T& x) {i >> . n).substr(m. log base e. y). int>::iterator p=a. y). int> a. // A 2-element struct a. x).. x mod y STRING (Variable sized character array) string s1.} // Default DEQUE (array/stack/queue) deque<T> is like vector<T>. // // // // // // // Open text file for reading Test if open and input available Read object from file Read char or line Read line into string s[n] Open file for writing Write to file ALGORITHM (A collection of 60 algorithms on sequences with iterators) min(x. // Number of elements (10) a. mon (0-11)..getline(s. p!=a. sqrt(x). // Decrease size by 1 a.a[9] are int (default size is 0) a.. n. !=. log10(x). // Add or replace element a["hello"] for (map<string. '\n').} UTILITY (Pair) pair<string.. // print "003. cerr << x << y << flush. cout << "x=" << 3 << endl. // // // // Smaller/larger of x. const T& x) {return o << . // Read char // Read line into char s[n] to '\n' (default) // Good state (not EOF)? // To read/write any type T: istream& operator>>(istream& i. // Same format. vector<T> e(d. // Removes a[0]. isdst asctime(p).c_str().begin().c[n-1] init to x T d[10].get(s). log(x). turn off assert NEW.begin().begin(). return i. // Absolute time in seconds or -1 if unknown tm* p=gmtime(&t). // pow(x. int> a("hello". shifts elements toward back a. x). IOMANIP (Output formatting) cout << setw(6) << setprecision(2) << setfill('0') << 3.getline(s. s2="hello".

Sign up to vote on this title
UsefulNot useful