A SUMMARY OF C++ FOR CGS 2425 STUDENTS Version 1/98 C++ SYNTAX EXPLANATION GENERAL: ---------------------------------------------------------------- i = 2 + 2; // statements end with a semicolon. float v; // velocity // double slash makes remainder of line a comment v = m /*mi*/ / h /*hr*/; // /* and */ delimit in-line comments A = a; // C++ is case sensitive, A and a are different. if (a == b) c = a; // most keywords are in lower case, e.g., if #include // includes external source code, typically used // to define library functions and classes. CONSTANTS: -------------------------------------------------------------- 123 // integer constant, base 10 0123 // octal constant, base 8, leading 0 0x12B // hexadecimal constant, base 16, leading 0x 1.2, .1, 1., 1.2e3, 1E20 // float constant, have . or e or E 'A', '\x41' // char constant, 2 A's; 41 hex is an ASCII 'A' // ASCII codes 'A'=65=0x41, 'a'=97=0x61, ' '=32=0x20, '0'=48=0x30 '\n' /*newline*/, '\a' /*bell*/, '\t' /*tab*/, '\\' /*backslash*/, '\'' /*single quote*/, '\"' /*double quote*/, '\0' /* same as '\x0' */ "He said \"I'm OK.\"\n"// string constant, \" is " 0 // logical constant, 0 means false else true const float pi = 3.14159;// a constant; Note: M_PI is defined in math.h // The const keyword may be used in many places to denote things that // cannot change, e.g. float average(const float x[], int n); #define pi 3.14159 // define a constant using a macro, outdated C DECLARATION STATEMENTS: --------------------------------------------------------// identifiers: 1 to 32 chars, a-z, A-Z, 0-9, or _, can't start w/ 0-9 int i; // declare a 2 byte signed integer,-32,768 to 32,767 unsigned int i; // declare a 2 byte unsigned integer, 0 to 65,535 long i; // declare a 4 byte signed integer, +-2,147,483,647 unsigned char i; // declare a 1 byte unsigned integer, 0 to 255 char i; // declare a 1 byte signed integer, -128 to 127 float x; // declare a 4 byte real, +-38 exponents double x; // declare a 8 byte real, +-308 exponents long double x; // declare a 10 byte real, +-4932 exponents int n = 10+15; // declare and initialize, can use expressions register int i; // use a CPU register to store i (if possible) int v1[9]; // declare a vector with cells 0 to 8, no cell 9 int m[5][10]; // declare a 2D array, reference with m[i][j], // notes: v1 and m are const pointers; v1[3], *(v1+3), (v1+1)[2] are // equivalent. Array data is stored row major order, m[i][j] is // same as *(m+i*10+j). C++ does'nt do range checking on arrays. char c; // declare a character char s1[10]; // declare an array of char, a string; can store up // to 9 chars plus a '\0' terminator. char s2[] = "ABCD"; // declare and initialize, sizeof(s2) is 5 because // of '\0' terminator. Note that the assignment statement // s2 = "EFGH" is invalid. Use strcpy or equivalent. int ok; // declare logical variable (0=False, Nonzero=True) enum { zero, one, two, // declare an enumeration list, a collection of six = 6, seven, ten };// constants, zero=0, one=1, seven=7, ten=8 enum {false, true}; // another enumeration list, false = 0, true = 1 float *p1; // declare a pointer to type float (one or more) char *p2; // declare a pointer to type char (or a string) typedef unsigned char byte;// declare a user-defined type called byte byte color; // declare color as a variable of type byte typedef float vect[5]; // declare another type called vect vect x1; // declare x1 as type vect struct r_type { // declare structure type, a record int data; // first member r_type *next; // second member; points to another record }; r_type r; // define r as a structure/record r.data = 17; // refer to a member of r typedef r_type* r_ptr; // declare a pointer type, r_ptr r_ptr p_r; // declare a pointer to r_type (or use r_type *p_r;) p_r = new(r_ptr); // allocate memory for a struct, p_r points to it p_r->data = 17; // refer to a member of a pointed to struct class point { // declare an object, see sample programs for more private: double x; // x coordinate of the point object double y; // y coordinate of the point object public: point(double x_initial, double y_initial); // constructor with args point(void); // another constructor, overloading void show(double factor=1.0);// member function, with default arg }; // sample program # 4 uses this class class circle : public point { // circle is derived from point EXPRESSIONS:------------------------------ // precedence: ( ) [ ] -> :: .; unaries ! ~ + - ++ - & sizeof new // delete; * / %; .* ->*; + -; << >>; < > <= >=; == !=; &; ^; // |; &&; ||; ?:; = += -= *= /= %= &= |= ^= <<= >>=; , // all are left to right except: unaries; :?; assignments * / + - // arithmetic operators, mult., divide, add, subtract i % 8 // modulo division, returns remainder, integer only (a+b)/(c+d) // parentheses can be used to force evaluation order 3 / 4 // integer division truncates 'A' + 1 // returns 'B' or 66 // in logical expressions, 0 means false, e.g. (4 > 3) evaluates to 1 > >= < <= == != // relational operators, e.g., x == y !flag // logical NOT flag1 && flag2 // logical AND flag1 || flag2 // logical OR i & 5 // bitwise AND, 12 & 10 evaluates to 8 (1100&1010) i | 5 // bitwise OR , 12 | 10 evaluates to 14 (1100|1010) i ^ 5 // bitwise XOR, 12 ^ 10 evaluates to 6 (1100^1010) ~i // bitwise complement ~5 evaluates to -6 (0xfffa) i >> 3 /*div by 8*/ // bit shift right, 5 >> 2 evaluates to 1 i << 3 /*mult by 8*/ // bit shift left, 5 << 2 evaluates to 20 ++a // pre increment; same as a = a + 1 or a += 1 a++ // post increment; increments but returns old a --a /* and */ a-- // decrement (pre and post) p = &x; // assign p the address of x x = *p; // assign x what's at location pointed to by p r.f // reference to field f of structure r p_r->f // reference to field f of structure pointed to // by p_r i = sizeof(r_type); // # of bytes in r_type, sizeof is an operator r_ptr = new(r_type); // allocates memory and assigns pointer to it p1 = new float[100]; // allocates 100 floats delete(r_ptr); // deallocates memory pointed to by r_ptr, the // amount of memory deallocated is the same as the // allocated. See malloc&free functions: stdlib.h expr ? expr1 : expr2 // returns expr1 if expr != 0 else expr2 i = (j=10, k=5, j+k);// comma operator, returns right most term, i==15 int(s1[0]) // typecasting: type(expr) or (type)expr EXECUTABLE STATEMENTS:------------------------- // Note: {stmt ... stmt} can be used in place of stmt expr; // an expression is a statement (by adding a ;) {stmt ... stmt} // compound statement x = y; // assignment statement; // assignment statements are really expressions, e.g. z = x += y; is ok. i += 1; // increment; equivalent to i = i + 1; or ++i; i -= 2; // i = i - 2; also *= /= %= &= |= ^= <<= >>= if(expr) stm1 else stm2// if statement; else is optional; stmt2 can be // another if statement for(i=1;i<=10;i++) stmt// for loop; same as i=1;while(i<=10){stmt;i++;} while(expr) stmt // while loop, question at top do stmt while(expr); // loop with question at the bottom switch(expr) { // does following: (put break in stmt to exit) case expr1 : stmt1 // if (expr == expr1) stmt1 case exprn : stmtn // if (expr == exprn) stmtn default: stmtd // if (none of the above) stmtd, } // the keyword default is optional break; // exit the innermost while, do, for, or switch continue; // go to bottom of innermost while, do or for return expr; // return to caller of this function, return expr do_it(x,y); // call a function, ignore returned val FUNCTION DECLARATIONS:------------------------- float cube(float x); // function prototype, placed at beginning of pgm float cube(float x) // function implementation, syntax: { return x*x*x; } // ret_type fun_name(arg_type arg_name,...) stmt // return stmt required unless ret_type is void int cube(int x) // overloaded definition of cube, cube(4) uses { return x*x*x; } // this, cube(4.0) uses original float version c = cube(a+b); // sample function call void get_x(float &x) // voided function, returns nothing. { cout << "Enter x: "; // &x means x is passed by address, not by val cin >> x; // return not needed for void functions } float sum(float x[], int n = 10) { // arrays always pass by address float s=0.0; // n has a default value of 10 when you call for(int i=0;i I/O cout << "x=" << x << "\n"; // unformatted write cin >> a >> b; // read statement; ' ', tab or return delimited cin.getline(s,10);// read up to 10 characters into s, a string // I/O cout << "x=" << setw(6) << setprecision(2) << x;// formatted I/O, needs // file I/O ifstream f_in; // declare an input file ofstream f_out; // declare an output file f_in.open("a.in",ios::in); // open a file for input if (!f_in) // check if open worked f_out.open(out,ios::out);// open a file for output, out has file name f_out.open(out,ios::app);// open a file for appended output prn.open("LPT1",ios::out); // open for output to printer f_in >> x; // read from file f_in.getline(s,80); // read lines f_out << x << "\n"; // write to file if (f_in.eof()) ... // check for end of file f_in.close(); // close a file //C I/O, defined in scanf("%d",&i); /* C read statement; in ; avoid */ printf("x=%6.2f\n",x); /* C formatted write; in ; avoid */ FILE *f; /* f is a file pointer */ f = fopen("test.dat","w"); /* open for writing */ fprintf(f, "%d %6d\n", i, i*i); /* write to a file */ f = fopen("test.dat","r"); /* open for reading */ fscanf(f, "%d %d", &i, &j); /* read from a file */ fclose(f); /* close a file */ COMMON LIBRARY FUNCTIONS: ----------------------------------------------------- // Notes: To use functions declared in a .h file, you need an #include // directive. This listing is not comprehensive. Use the help system // or a book to see other available functions and header files. //conio.h int getch(); // read a keystroke from the keyboard, w/o echo int getche(); // read a keystroke from the keyboard, w/ echo getch & getche are used by Turbo C++ programmers to read keys w/o waiting for the Enter key. When you press an ASCII key you get the that character. When you press other keys, e.g. PgUp, you get a '\0'; another call is required to get the extended key code: F1=59,shift/F1=84,ctrl/F1=94,alt/F1=104,PgUp=73,PgDn=81,up=72,dn=80 left=75,right=77,home=71,end=79,del=83,ins=82 //ctype.h (all is... functions return nonzero for true or 0 for false) int isalpha(int c) // A-Z or a-z ? int islower(int c) // a-z ? int isupper(int c) // A-Z ? int isdigit(int c) // 0-9 ? int isxdigit(int c) // 0-9 or A-F or a-f ? int isalnum(int c) // 0-9 or A-Z or a-z ? int iscntrl(int c) // ASCII 0-31 ? int isgraph(int c) // not cntrl or space ? int isprint(int c) // ASCII 32-127 ? int ispunct(int c) // any punctuation ? int isspace(int c) // ' ','\n','\r','\t','\v' ? int tolower(int c) // converts to lower case, e.g., c = tolower(c); int toupper(int c) // converts to upper case //fstream.h (see I/O above) //iomanip.h functions: (iomanip.h includes iostream.h) setfill(' ') // sets fill char for next item in stream setprecision(int d) // sets decimal digits for next item in stream setw(int w) // sets width of next numeric in stream //iostream.h functions: (in addition to << and >> overloading) cout.precision(int d)// sets default decimal digits for output cout.setf(ios::showpoint|ios::fixed);// force showing decimal point cout.width(int w) // sets width for next numeric output; use setw //math.h (all trig functions work in radians) double ceil(double x)// returns integer above or equal to x double cos(double x) double exp(double x) // e to the x double fabs(double x) double floor(double x) double fmod(double x,y)// float modulo division, % operator for int double log(double x) // natural log double log10(double x) double pow(double x,y) // x to the y power int rand(void) // returns a random integer 0 to 32767 double sin(double x) double sqrt(double x) void srand(unsigned seed)// sets random seed double tan(double x) //stdio.h char *gets(char *s) // reads a string from keyboard int puts(const char *s) // prints a string on the screen char *fgets(char *s,int len,FILE *dev) // reads a string from a device int fputs(const char *s,FILE *dev) // output a string to a device //stdlib.h void *malloc(unsigned size) // allocates size bytes of memory, // returns pointer; use new and delete void free(void *block) // unallocates a block of memory int atoi(const char *s) // converts string s to int int atol(const char *s) // converts string s to long int atof(const char *s) // converts string s to float void exit(int i) // halts program with exit code i //string.h char *strcpy(char *s1,const char *s2)// copies s2 to s1, returns s1 char *strcat(char *s1,const char *s2) // concatenates s2 to end of s1, // returns s1 int strcmp(const char *s1,const char *s2) // 0 if s1 equal s2, // < 0 if s1 < s2, > 0 if s1 > s2 unsigned strlen(const char *s1)// length of s1, not including '\0' char *strchr(const char *s, int c)// scans s for the 1st occurence of c char *strstr(const char *s1, const char *s2) // finds 1st s2 in s1 char *strtok(char *s1, const char *s2) // scans s1 for 1st token not // contained in s2 void *memmove(void *dest, void *src, unsigned n) // copy n chars void *memset(void *dest, char ch, unsigned n) // set n bytes to ch //graph.h (Turbo C++ specific) see sample program #4 //dos.h (Turbo C++ specific) many more functions available, use help external char *_argv[] // command line arguments (global var) external int _argc // # of command line args (global var) void delay(unsigned milliseconds)// delays execution specified time void sound(unsigned frequency) // makes tone on computer speaker (Hz) void nosound(void) // stops tone on computer speaker int peek(unsigned seg, unsigned ofs) // get a word from memory char peekb(unsigned seg, unsigned ofs) // get a byte from memory void poke(unsigned seg, unsigned ofs, int val) // change a word in mem void pokeb(unsigned seg, unsigned ofs, char val)// change a byte in mem SAMPLE PROGRAM # 1: SQUARE ROOT COMPUTATION ----------------------------------- #include // Sample program output #include // int main(void) { // Enter an x: 12.2 float x; // SQRT = 3.49 cout << "Enter an x: "; cin >> x; cout << "SQRT = " << sqrt(x) << endl; return 0; } SAMPLE PROGRAM # 2: FUNCTION EXAMPLES ----------------------------------------- #include float cvt(float x); // function prototype for cvt, value argument void get_x(float &x); // function prototype for getx, address argument int main(void) { // the main program float x; get_x(x); // call voided function, a subroutine cout << x << " feet = " << cvt(x) << " inches\n";// use cvt return 0; } float cvt(float x) { // implementation of cvt const float in_per_ft = 12.0; return x*in_per_ft;} void get_x(float &x) { // implementation of getx cout << "Enter x: "; cin >> x; // calling pgm sees change to x } SAMPLE PROGRAM # 3: FILE I/O EXAMPLE ------------------------------------------ #include typedef unsigned char boolean; enum {false, true}; int main(void) { ofstream out_file; ifstream in_file; char line[81]; int i = 1; boolean done; out_file.open("test.dat"); do { out_file << i << ' ' << i*i << '\n'; } while (i++ < 5); out_file.close(); in_file.open("test.dat"); done = false; do { in_file >> i; if (in_file.eof()) done = true; else cout << i; } while (!done); in_file.close(); return(0); } SAMPLE PROGRAM # 4: POINTER EXAMPLE ------------------------------------------- #include main() { int a[4] = {2,4,6,8}; // an array int *p; // a pointer cout << " A" << a[0] ; p = a; cout << " B" << *p ; cout << " C" << *a ; cout << " D" << a[2] ; cout << " E" << p[2] ; cout << " F" << *(p+2) ; cout << " G" << *(a+2) ; cout << " H" << (a+1)[1] ; int *q[4]; q[1] = a; q[2] = a+2; cout << " I" << *q[1] ; cout << " J" << *q[2] ; cout << " K" << q[1][2] ; cout << " L" << *(q[1]+2) << endl; return 0; } SAMPLE PROGRAM # 5: GRAPHICS EXAMPLE ------------------------------------------- // This program contains Turbo C++ specific functions. // You must have egavga.bgi in the current dir to run this program. #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int xmax, ymax; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { cout << "Graphics error: " << grapherrormsg(errorcode) << "\n"; cout << "Press any key to halt:"; getch(); exit(1); } setcolor(getmaxcolor()); xmax = getmaxx(); ymax = getmaxy(); line(0, 0, xmax, ymax); // draw a diagonal line /* clean up */ getch(); closegraph(); return 0; } SAMPLE PROGRAM # 6: OBJECT IMPLEMENTATION EXAMPLE (3 files) -------------------- *** MAIN PROGRAM FILE, POINTDEM.CPP *** #include #include "POINT.H" int main(void) { Point p1(1.5, 4); // declare an object with initial values Point p2; // declare an object with default initial values cout << "Class p1 contains : "; p1.Show(); // display values in p1 cout << "Class p2 contains : "; p2.Show(); // display values in p2 p2 = p1; // use assignment operator cout << "New p2 values are : "; p2.Show(12); // display new values in p1 return 0; } *** HEADER FILE, POINT.H *** class Point { // class definition for point private: double x; // the x coordinate of the point object double y; // the y coordinate of the point object public: Point(double x_initial, double y_initial); // constructor with args Point(void ); // constructor without args void Show(double factor=1.0); // member function, with default arg }; *** IMPLEMENTATION FILE, POINT.CPP *** // This file implements the functions of the point object #include #include "POINT.H" Point::Point( double x_initial, double y_initial ) {// constructor x = x_initial; y = y_initial; } Point::Point(void) { // constructor x = 0.0; y = 0.0; } void Point::Show(double factor) { // displays coords cout << "x = " << x*factor << ", y = " << y*factor << '\n'; }