Summary of the "C++" language Includes draft ANSI STD 2 Dec 1996 Program Structure: The "main" function and one or more other functions may be in a file. There are no procedures or subroutines, a function may be used like a procedure with the function return value, if any, just ignored. Files are compiled with the some C++ compiler such as g++, Borland, Microsoft, etc. Some typical file structures: int main(void) // This could be a complete program { sequence_of_statements return 0; } #include void main(void) // main function and other functions { // in same file local_declarations sequence_of_statements } void function_1( formal_parameters ) // function definitions { // may not be nested local_declarations sequence_of_statements } some_type function_2(void) // no formal parameters { local_declarations sequence_of_statements } // as many functions as desired #include // a main function that can get command line global and/or external declarations int main(int argc, // argc, the number of command line items char *argv[]) // argv, command line items including calling // program name as argv[0] { local_declarations sequence_of_statements } Executable statements: Statements end with a semicolon or brace. A compound statement may be made from a sequence of statements by enclosing them in braces. { statement ; statement ; statement ; } is a statement Assignment statements (with some short hand notation) x = 10; x = x+1; ++x; // same as x = x+1; x++; // same as x = x+1; sets a false flag to true --x; // same as x = x-1; x--; // same as x = x-1; x = x+20; x += 20; // same as x = x+20; x -= 20; // same as x = x-20; x *= 20; // same as x = x*20; x /= 20; // same as x = x/20; x %= 20; // same as x = x%20; modulo x <<= 2; // same as x = x<<2; shift left x >>= 2; // same as x = x>>2; shift right x &= 20; // same as x = x&20; and bits x ^= 20; // same as x = x^20; exclusive or bits x |= 20; // same as x = x|20; or bits x = (y=3,y++) // same as y=3; x=y; y=y+1; x = who ? 3 : y; // same as if(who)x=3; else x=y; x = sin(x) ; // function call x = mat[i][j] ; // subscripting Function call with return ignored: (a procedure in other languages) go_do_it(); // no actual parameters exit(0); // special function that terminates execution Unconditional branches: break; // immediate exit from loop or switch continue; // immediate jump to end of loop ( not exit ) also used to exit a switch in a loop return; // immediate exit from function, no value return exp; // exit from function returning value of exp goto label; // unconditional jump ( should not be needed. ) label: statement; // label definition ( should not be needed. ) Conditional branching: if ( expression ) // condition may be any expression, != 0 is true { statement_sequence // executed if expression !=0 } else { statement_sequence // executed if expression ==0, i.e. false } if-else-if ladder structure if(exp_1) // the first expression that is true, e.g. exp_i statement_1; // causes statement_i to be executed else if(exp_2) // then jump to end after statement_n statement_2; // use { } even if only one statement for safety else if(exp_3) // when doing changes or maintenance statement_3; ... else statement_n; Switch statement: switch ( expression ) // constants must be unique { case constant_1: // do nothing for this case break; case constant_2: // drop through and do same as constant_3 case constant_3: statement_sequence // can have but does not need { } break; case constant_4: statement_sequence // does this and next also case constant_5: statement_sequence break; default: // default executes if no constant equals statement_sequence // the expression. This is optional } An expression can be almost anything. e.g. Pi-37.026E5b Iteration statements: for ( initialization ; condition ; increment ) { statement_sequence } // The flow sequence is : // initialization // test condition and exit if false // statement_sequence // increment // loop back to test condition examples: infinite loop: for(;;){ statements ... if(stuff)break; ... } self initialized: for(int i=0; i // one or more dummy names for types typ funct( typ x, typ y, typ z) { typ a, b; // substitution is made everywhere a = x + y; // for the actual types, including operations b = y - z; return a * a / b; } #include int main() { int i = funct(3, 5, 7); // funct( any numeric type 3 actual parameters ) long j = funct(3L, 5L, 7L); // can also be in expressions unsigned k = funct(3U, 5U, 7U); float x = funct(3.1F, 5.2F, 7.3F); double y = funct(3.1, 5.2, 7.3); cout << i << " int, " << j << " long, " << k << " unsigned, " << x << " float, " << y << " double.\n"; return 0; } // end main Function definition: Function Prototype: type function_name(type_1 v1, type_2 *v2, type_3 &v3, const type_4 v4); // e.g. char * strcpy(char * s1, const char * s2); // *v2 says pass a pointer to v2 // &v3 says pass by reference // const type_4 v4 says v4 is an 'in' parameter a prefix of static makes the function visible only in this file Function Definition: type function_name(int a, float b, const char * ch,...){ function_body } // only parameters passed by pointer or reference can // be modified in the calling function, // a local copy will be made and can be modified, // unsafely, unless const is used char * strcpy( char * s1, const char * s2 ) { statements } obsolete example of a function and call passing the address of a scalar void func(int *num) { *num *= *num; // square num back in its place } ... func(&i); // call, passing address of i, the lvalue of i ( yuk!) C++ example of a function and call passing a reference of a scalar void func(int &num) // says do type checking and pass by reference { num = num*num; // square num back in its place } func(i); // just a normal call, the compiler knows to pass a reference Reserved words:(Keywords) must be lower case. asm assembly language, destroys portability auto optional local declaration bool basic declaration of type Boolean break used to exit loop and used to exit switch case choice in a switch catch catch block that handles a thrown exception char basic declaration of a type character class start a class definition const prefix declaration meaning variable can not be changed const_cast continue go to bottom of loop in for, while and do loops default optional last case of a switch delete free space created by 'new' ( do not use 'free' ) do executable statement, do-while loop double basic declaration double precision floating point dynamic_cast else executable statement, part of "if" structure enum basic declaration of enumeration type explicit extern prefix declaration meaning variable is defined externally false value of type bool float basic declaration of floating point for executable statement, for loop friend a function that can see internal stuff in a class goto jump within function to a label if executable statement inline expand the code rather than call it int basic declaration of integer long prefix declaration applying to many types mutable namespace new get storage, free storage later with 'delete' ( do not use malloc) operator followed by an operator symbol, can define overloaded functions private the stuff after this is not visible outside the class protected the stuff after this is for classes that inherit this class public the stuff after this is visible outside the class register prefix declaration meaning keep variable in register reinterpret_cast return executable statement with or without a value short prefix declaration applying to many types signed prefix declaration applying to some types sizeof operator applying to variables and types, gives size in bytes static prefix declaration to make local variable static static_cast struct declaration of a structure, like a record switch executable statement for cases template proposed template functions this the class object, used in 'return' statements and others throw throw an exception true value of type bool try try block that precedes a catch block typedef creates a new type name for an existing type typeid union declaration of variables that are in the same memory locations unsigned prefix declaration applying to some types virtual this type of function is hidden if defined by an inheritor void declaration of a typeless variable or no formal parameters volatile prefix declaration meaning the variable can be changed at any time wchar_t basic declaration for type wide character (internationalization) while executable statement, while loop or do-while loop also reserved are names that start with __ ( double underscore ) avoid names that start with _ ( single underscore ) except for special use Operators and punctuation as single special characters: ! % ^ & * ( ) - + = { } | ~ [ ] \ ; ' : " < > ? , . / # Operators and other groups of special characters -> ++ -- .* ->* << >> <= >= == != && || *= /= %= += -= <<= >>= &= ^= |= :: // /* */ ## <% %> <: :> %: ... %:%: Trigraphs for users who do not have certain special characters: ??= # ??( [ ??/ \ ??) ] ??' ^ ??< { ??! | ??> } ??- ~ Character constants for special characters: new line NL '\n' '??/n' in trigraph notation horizontal tab HT '\t' " col 1 \t col 2 \t \n" in string notation vertical tab VT '\v' backspace BS '\b' carriage return CR '\r' form feed FF '\f' alert BEL '\a' backslash \ '\\' question mark ? '\?' single quote ' '\'' double quote " '\"' octal character 377 '\377' hex character C1 '\xC1' The proposed standard has not yet addressed international character sets where 16, 24 or 32 bit characters may be used. 'AB' is undefined. Header files: From ANSI C : assert.h ctype.h errno.h float.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stddef.h stdio.h stdlib.h string.h time.h and additional for C++ : new.h complex.h ... more coming as standard evolves Declarations have the forms: basic_type variable ; basic_type variable_1, variable_2=value; // only initializes variable_2 prefix_type(s) basic_type modifier_type variable , variable ,... ; Atype variable[val][val]...[val]={data,data,...}; struct struct_name { // struct_name is now a type name Atype variableA; // any declaration Atype variableB; ... Atype variable; } variable1, variable2, ... ; // variables are optional struct struct_name { // struct_name is now a type name Atype variableA : length1; // any declaration : length in bits Atype variableB : length2; // type is int, unsigned or signed ... Atype variableN : lengthN; } variable1, variable2, ... ; // variables are optional, they can // also be arrays and pointers struct_name another_variables; // don't need extra 'struct' in C++ union union_name { // union_name is now a type name float variable_1; // variable_1 overlays variable_2 int variable_2; ... Atype variable; } variable1, variable2, ...; // variables are optional union_name variableX ; // use an existing union definition variableX.variable1=3.5; // set a float component variableX.variable2=7; // integer clobbers float enum enum_type // enum_type is now a type name { enumeration_name_1, // establishes enumeration literals enumeration_name_2=number, // assigns value to enumeration lit ... enumeration_name_n } variable1, variable2, ...; // variables are optional enum_type variable; // use an existing enum type definition enum_type variable = enumeration_name_1; // normal initialization typedef existing_type new_type_name ; // e.g. typedef unsigned int size_t typedef char * string; // 'string' is now type char * class aClass // define a class { friend some_other_class; // if two mutually related classes public: // stuff after this is visible outside double myStuff; virtual void function_1(f_p's); // can be redefined when inherited void aMethod(void){myStuff=3.5}; // an inline defined method aClass(); // special function, the constructor ~aClass(); // special function, the destructor protected: // stuff after this is for inheritors virtual any funct2(any)=0; // pure virtual, makes class abstract. int for_descendents; private: // stuff after this only for inside int HandsOff; MyFunction(formal_parameters); // full definition later inline Funct(const int i){HandsOff=i;}; // full definition here }; aClass::aClass() // all functions not defined above { // must be defined ( body implemented ) // code for constructor if not inlined above } aClass::MyFunction(formal_parameters) { // code for function if not inlined above } aClass class_variable; // make an object of type 'aClass' aClass *class_pointer = & class_variable; // make a pointer to above aClass *class_pointer = new aClass(); // a typical class pointer, constructed class_variable.myStuff = 3.51; // set a variable in a class object class_variable.aMethod(); // use a function from a class object class_pointer->myStuff = 3.52; // set a variable using a pointer class_pointer->aMethod(); // use a function via a class pointer class aDerivedClass : public aClass // public may be protected or private { double more_stuff; void aNewMethod(void){myStuff=3.6}; // an additional method virtual void function_1(f_p's); // this will do something different } // this derived class has all the stuff from 'aClass' plus more void aDerivedClass::function_1(f_p's) { whatever_the_function_is_to_do; } Basic types: char character type, usually one byte ( a string is array of char ) bool boolean type has values true and false, usually one byte int integer type, usually 2 or 4 bytes ( default ) may be 8 bytes float floating point type, usually 4 bytes IEEE 32 bit double floating point type, usually 8 bytes IEEE 64 bit void no type, typeless enum enumeration type ( user defines the type name ) Type modifiers, prefix for basic types: signed has a sign ( default ) unsigned no sign bit in variable long longer version of type (short or long alone means short int or short shorter version of type long int because int is the default ) const variable can not be stored into Storage class, prefix for types: auto local variable ( default, not really needed ) static persistent when function exits, not auto volatile can change from outside influence extern variables are defined elsewhere, externally register assign variable to register, usually ignored by modern compilers Other stuff: inline expand code inline rather than call the function(only a hint) virtual use unless over ridden by later definition, functions only friend can access internals of other classes class a basic data structure type struct a basic data structure type union overlay previously defined data types Modifier type: * makes a pointer to what follows & makes a reference to what follows int i = 1000; // allocate storage and initialize value to 1000 int *ptr; // allocate storage for a pointer, garbage initially ptr = &i; // ptr now points to i *ptr = 100; // change value of i to 100 Samples of variable declarations: auto xyz; // int is default, bad practice unsigned long int pqr; extern int global_stuff, remote_function(); register int quick, *my_ptr; void just_do_it(); // no return value char *my_string; // typedef char * string; then string my_string; char *argv[]; struct account{ char name[20]; float bal; unsigned sex:1; } person; struct account *p; p=&person; // p is pointer to person (*p).bal=100.00; // older usage p->bal=100.00; // better usage, means same as above Automatic setting of array size based on data char msg[]="Set the size to correct length \n"; char *p="auto length"; char ary[3]="Element in an array of messages"; // 3 items, 0,1 and 2 float matrix[][3]={1.,2.,3.,4,.5.,6.}; // fills in blank with 6 float ***a; // (a+10)[0][0][0] is a way to index 3 dimensional array // old usage, not liked in C++ int ia[4][3]= {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 0, 1}}; // initialization using nested {{},{},{},{}}; Getting storage/ freeing storage ( do not use malloc and free ! ) aClass *p=new aClass; delete p; Expressions: variable names start with alphabetic or underscore, followed by alphabetic, numeric or underscore I some_name ELSE Else z999 __do_not_use numbers decimal integer ( no U or L yields shortest type ) (int) 1 12349 (unsigned int) 1U 12349U (long int) 1L 1234569L (unsigned long int) 1UL 1234569UL floating point ( default is double ) (double) .1 1. 1.5E-20 (float) .1F 1.F 1.5E-20F (long double) .1L 1.L 1.5E-20L octal ( 0 prefix ) and hexadecimal ( 0x prefix ) integers ( no U or L yields shortest type ) (int) 01777 0x248F (unsigned int) 01777U 0x248FU (long int) 01777L 0x248FL (unsigned long int) 01777UL 0x248FUL character single character between apostrophes plus special backslash codes 'a' 'Z' '\n' string characters between quotes plus special backslash codes a null is automatically placed at end of every string "Hello" "good by \n" let exp, exp1, exp2, exp3 etc. stand for expressions expressions are: variables numbers characters strings unary_operator expression expression binary_operator expression ( expression ) variable post_operator ( ++ and -- ) operator precedence and associativity is: Assoc highest : ( ) [ ] -> . x++ x-- :: LR ! ~ + - ++x --x * & sizeof (type) new delete RL .* ->* LR * / % LR + - LR << >> LR < <= > >= LR == != LR & LR ^ LR | LR && LR || LR ? : RL = += -= *= /= %= >>= <<= &= ^= |= RL lowest : , LR LR means associate left to right, RL means associate right to left operator definitions ( in executable code, highest precedence first ) : ( ) grouping parenthesis, function call [ ] array indexing, also [ ][ ] etc. -> selector, structure pointer employee->wage = 7.50 ; . select structure element employee.wage = 7.50 ; :: indicates member of a class ! relational not, complement, ! a yields true or false ~ bitwise not, ones complement, ~ a ++ increment, pre or post to a variable -- decrement, pre or post to a variable + unary plus, + a - unary minus, - a * indirect, the value of a pointer, * p is value at pointer p address & the memory address, & b is the memory address of variable b sizeof size in bytes, sizeof a or sizeof (int) (type) a cast, explicit type conversion, (float) i, (*fun)(a,b), (int *)x new allocate storage ( replaces malloc ) delete deallocate storage ( replaces free ) .* pointer to member operator, to class ->* pointer to member operator, to class pointer * multiply, a * b / divide, a / b % modulo, a % b + add, a + b - subtract, a - b << shift left, left operand is shifted left by right operand bits >> shift right, left operand is shifted right by right operand bits < less than, result is true or false, a < b <= less than or equal, result is true or false, a <= b > greater than, result is true or false, a > b >= greater than or equal, result is true or false, a >= b == equal, result is true or false, a == b != not equal, result is true or false, a != b & bitwise and, a & b ^ bitwise exclusive or, a ^ b | bitwise or, a | b && relational and, result is true or false, a < b && c >= d || relational or, result is true or false, a < b || c >= d ? exp1 ? exp2 : exp3 result is exp2 if exp1 != 0, else result is exp3 = store += add and store -= subtract and store *= multiply and store /= divide and store %= modulo and store <<= shift left and store >>= shift right and store &= bitwise and and store ^= bitwise exclusive or and store |= bitwise or and store , separator as in ( y=x,z=++x ) zero evaluates to false ( a null pointer has a zero value ) non zero evaluates to true ( !null_pointer is true ) * is heavily overloaded, so is & Backslash codes for in character constants and strings: these can be used as characters when enclosed in apostrophes \a alert, audible alarm, bell, ^G \b Backspace, ^H \f Form feed, new page, ^L \n New line, carriage return and line feed, ^M^J \o Octal constant, \oddd, \ddd \r Carriage return, no line feed, ^M \t Horizontal tab, tab, ^I \v Vertical tab, ^K \x Hexadecimal constant, \xdd 0 <= d <= F \0 null, zero value character, ^@ \" Quote character \' Apostrophe character \\ Backslash character \? Question mark character \ddd Octal character value 0 <= d <= 7 Format commands for printf() and scanf() fprintf,fscanf sprintf,sscanf ( these are still needed, but use type checked 'cin >>' and 'cout <<') %c a single character, char %d a decimal number, int %hd is for short %ld is for long %e a floating point number, float in scientific notation, %E for 1.0E-3 %le is for double, %Le is for long double %f a floating point number with decimal point %10.4f 10 wide .dddd %lf is for double, %Lf is for long double %g a floating point number, %f or %e as needed, %G for capital E %lg is for double, %Lg is for long double %h an unsigned hexadecimal short integer (scanf only), old usage %i an integer, int %hi is for short int, %li is for long int %n pointer to integer to receive number of characters so far, int *i %o an unsigned octal number, unsigned int %ho and %lo for short and long %p a pointer, void **x %s a string ( must be null terminated ! ), use %s for scanf %u an unsigned decimal integer (printf only), unsigned int %hu %lu %x a hexadecimal number, %X for capital ABCDEF, unsigned int %hx %lx [...] string, x[] % none Text may be around format characters for printf(), The list follows the single quoted format string. Output is right justified unless format %-s or %-10.4f is used. %+... causes plus sign to be printed. %* suppresses assignment, no store, in scanf(). %# converts value to alternate form. Field is expanded if not enough room to print. numeric data into scanf() must be separated by space, tab or newline, not comma characters between % in scanf() format must be in input and are ignored Preprocessor directives: #include "stdio.h" search current working directory first #include search command line directory then system #define TRUE 1 Obsolete, use const true=1; #define do_it(a) ((a<0)?-(a):(a+1)) macro substitution, beware! #define note /* this comment gets inserted every \ time note appears */ backslash \ at end of line means continue #undef TRUE undefines a previously defined macroname #error stop compiling at this point #if expression conditional compilation, start if structure #elif expression else if expression != 0 compile following code #else else compile following code #endif end of conditional compiling #ifdef macroname like #if, compiles if macroname defined #ifndef like #if, compiles if macroname undefined #line number [filename] set origin for __LINE__ and __FILE__ #pragma gives the compiler commands Supplement on "static" in classes, example // static.cc test various cases note //! is about 'static' #include class Base { public: Base(void) {B1=1; B2=2; B3=3;} static void BF1(void); //! definition can not go here void BF2(void) { cout << B1 << " " << B2 << " BF2 in Base \n"; B2=5; } private: static B1; //! no =1; here int B2; int B3; }; int Base::B1 = 1; //! has to be outside of class but not in 'main' //! only one per total program, not in .h file void Base::BF1(void) //! can not use word static in front of this { cout << B1 << " BF1 static in Base \n"; //! can not use B2 or B3 in here B1=4; } int main(void) { Base a, b; a.BF2(); a.BF1(); //! object can be used, any object, same result a.BF2(); b.BF2(); Base::BF1(); //! no object needed, but do need Base:: syntax b.BF2(); return 0; } // results, note B1 is changed in object 'a' and B1 gets changed also in 'b' // while B2 is changed in object 'a' and 'b' unaffected // 1 2 BF2 in Base B1==1, B2==2, B2=5 in 'a' // 1 BF1 static in Base B1==1, B1=4 global // 4 5 BF2 in Base B1==4, B2==5, B2=5 in 'a' // 4 2 BF2 in Base B1==4, B2==2, B2=5 in 'b' // 4 BF1 static in Base B1==4, B1=4 global // 4 5 BF2 in Base B1==4, B2==5, B2=5 in 'b'