// /* // // // // // // // // // 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

// Call to static member ..operator+(y) int operator-().} // Allows int(t) friend void i(). invalid pointers.operator-() T(): x(1) {} // Constructor with initialization list T(const T& t): x(t. } argv is an array of argc strings from the command line. Unary operators and assignment evaluate right to left. // Member function void g() {return.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.x) {} // Copy constructor T& operator=(const T& t) {x=t. // Allow t=T(3) but not t=3 operator int() const {return x. // Does not modify any data members int operator+(int y). // -t means t.} // this is address of self (means x=x. Every program consists of a set of a set of global variable declarations and a set of function definitions (possibly in separate files). May access y but not x class Z {}. which is undefined. else z // Throw exception. // Initialization of static member (required) T::l(). evaluates to new value // Bitwise complement of x // true if x is 0.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. } or int main(int argc. It may be declared first and defined later. main returns status 0 if successful. // Global function i() has private access friend class U. use .. 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.} // Inline member function void h() const. returns y (seldom used) EXPRESSIONS x | y x && y Operators are grouped by precedence. All others are left to right. 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.x.Function parameters and return values may be of any type. 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. x << y x >> y x x x x < y <= y > y >= y // x shifted y bits to left (x * pow(2. Precedence order is not affected. highest first. aborts if not caught // evaluates x and y. checked at run time // Converts x to a T.) int T::y = 2. // Shared code._cast<T>(x)) // Multiply // Divide (integers round toward 0) // Modulo (result has sign of x) // Add. There are no run time checks for arrays out of bounds. // Member data void f(). evaluates to new value (prefix) // Subtract 1 from x. y) new T[x] delete p delete[] p (T) x x * y x / y x % y x + y x . 1 or higher for errors. also -= *= /= <<= >>= &= |= ^= // y if x is true (nonzero). void T::f() { // Code for member function f of class T this->x = x. // Data shared by all T objects static void l(). or &x[y] // Subtract. T::X // Name X defined in class T N::X // Name X defined in namespace N ::X // Global name X t. return *this.y) T(x. or number of elements from *x to *y x || y (0)) x = y x += y x ? y : z throw x x .. char* argv[]) { statements..x p->x a[i] f(x. evaluates to original x (postfix) // Subtract 1 from x. one of which must be: int main() { statements. // Nested class T::Z typedef int V. returns new value of x // x = x + y. evaluates to original x // Type of x // Equals typeid(x) if x is a T // Converts x to a T. By convention. New operators may not be created. // t+y means t. // Members of class U have private access static int y. Operators except :: .* ?: may be overloaded.. } // Assignment operator ~T(). // Destructor (automatic cleanup routine) explicit T(int a). . etc. // T::V means int }. Precedence does not affect order of evaluation. y)) // x shifted y bits to right (x / pow(2. A function must either be declared or defined before it is used. Functions with different parameters may have the same name (overloading). 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. 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.

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

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

Sign up to vote on this title
UsefulNot useful