################## C++ Commands ################## ========== Basics ========== -------- Output: -------- .. code-block:: bash cout << Variable; ------- Input: ------- .. code-block:: bash cin >> Keyboard; cin >> a >> b; => cin>>a; cin>>b; .. code-block:: bash #include int main() { string mystr; getline (cin, mystr); } --------------- Stringstream: --------------- .. code-block:: bash #include int main() { string mystr; float price=0; getline(cin, mystr); stringstream(mystr) >> price; } ----------------- Logic Operators: ----------------- .. code-block:: bash && And || Or ! Not ? Conditional condition ? result1 : result2 , operator ===================== Control structures: ===================== -------------- Conditional -------------- .. code-block:: bash if (condition) { statement1; statement2; } else statement3; ---------------------- Iteration structures ---------------------- .. code-block:: bash while (expresion) statement .. code-block:: bash do statement while (condition); .. code-block:: bash for (initialization; condition; increase) statement; for (int n=10; n>0; n--) { cout << n << ", "; } for (n=0, i= 100; n!=i; n++, i--){ //wathever here... } .. code-block:: bash break statement continue statement goto statement .. code-block:: bash cstdlib library void exit(int exitcode); .. code-block:: bash do statement while (condition); .. code-block:: bash switch (expression) { case constant1: group of statements1; break; case constant2: group of statements2; break; . . default: default group of statements } --------------- Functions(I) --------------- .. code-block:: bash type name(parameter1, parameter2, ...) (statements) scope o variables .. code-block:: bash #include //Global variables int integer; char aCharacter; char string[20] main() { //local variables unsigned short age; float ANumber, AnotherOne; //instructions .... } Functions with no type .. code-block:: bash void printmessage() { cout<< "I'm a function!"; } Call the function (Use parentheses) printmessage(); --------------- Functions(II) --------------- Arguments passed by value and by reference By value: .. code-block:: bash int x=5, y=3, z; z=addition(x,y); By reference: .. code-block:: bash void duplicate(int& a, int& b, int& c) // the values of a, b, c was passed by reference they could change their values into the function. Overloaded functions: .. code-block:: bash // overload function #include using namespace std; int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int manin() { int x=5, y=2; float n=5.0,m=2.0; cout<< operate (x,y); cout<< "\n"; cout<< operate (n,m); cout << "\n"; return 0; } Inline functions, the code of the function is inserted on the main code each time the function is called: .. code-block:: bash inline type name (arguments ...) (instructions ...) Recussivity: .. code-block:: bash long factorial (long a) { if (a>1) return (a * factorial(a-1)); else return(1); } Declaring functions .. code-block:: bash //declaring function prototypes # include using namespace std; void odd (int a); void even (int a); int main() { int i; do{ cout<< "Type a number (0 to exit): "; cin>>i; odd(i); } while (i!=0); return 0; } void odd (int a){ if (a%2)!=0) cout << "Number is odd. \n"; else even(a); } void even (int a){ if (a%2)==0) cout << "Number is even. \n"; else odd(a); } ================= Arrays ================= Declaration: .. code-block:: bash int billiy[5]; Initiallizing: .. code-block:: bash int billy[5]={16,2,77,40,12071}; Accesing: .. code-block:: bash a= billi[2]; Array as parameters: .. code-block:: bash void procedure(int arg[]); Pass this function an array: .. code-block:: bash int myarray[40]; procedure(myarray); ---------------------- Caracter sequences ---------------------- .. code-block:: bash char jenhy[20]; char myword[]={'H', 'e','l','l','o','\0'}; char myword[]="Hello"; ============== Pointers ============== ------------------------ Reference operator (&) ------------------------ .. code-block:: bash ted= &andy; Pos 1776 +-------+------+ | Name | Age | +=======+======+ | andy | 25 | +-------+------+ +------+------+ | Name | Year | +======+======+ | ted | 1776 | +------+------+ -------------------------- Dereference operator (*) -------------------------- .. code-block:: bash bet= \*ted; \*ted=andy; +--------+----------+ | \*ted | 25 | +========+==========+ | bet | 25 | +--------+----------+ --------------------------------------- Declaring variables of pointer types --------------------------------------- .. code-block:: bash type* name; int* number; char* Character; float* greatnumber; .. code-block:: bash //my first pointer #include using namespace std; int main() { int firstvalue, secondvalue; int* mypointer; mypointer = &firstvalue; *mypointer=10; mypointer = &secondvalue; *mypointer=20; cout<<"firstvalue is "<< firstvalue << endl; // prints 10 cout<<"secondvalue is " << secondvalue << endl; // prints 20 return 0; } .. code-block:: bash //my first pointer #include using namespace std; int main() { int firstvalue=5, secondvalue=15; int * p1, * p2; p1= &firstvalue; p2= &secondvalue; *p1=10; *p2=*p1; p1=p2; *p1=20; cout<< "firstvalue is " << firstvalue < using namespace std; int main() { int numbers[5]; int * p; p= numbers; *p=10; p++; *p=20; P=&numbers[2]; *p=30; P=numbers+3; *p=40; p= numbers; *(p+4)=50; for (in n=0; n<5; n++) cout numbers[n]<< ", "; //prints 10, 20, 30, 40, 50, return 0; } ------------------------ Pointer initialization ------------------------ .. code-block:: bash int number; int *tommy=&number; char *terry="Hello"; ----------------------- Pointer arithmetics ----------------------- .. code-block:: bash char *mychar; short *myshort; long *mylong; mycharr++; myshort++; mylong++; Equivalent to: .. code-block:: bash mychar=mychar + 1; myshort=myshort +1; mylong=mylong+1; and equivalent to the ambiguous writing: .. code-block:: bash *mychar++; *myshort++; *mylong++; Because ++ has greater precedence than \*. Different to: .. code-block:: bash (*mychar)++ Avoid unexpected results by using parentheses. --------------------------- pointers to pointers --------------------------- .. code-block:: bash char a; char *b; char **c; a= 'z'; b= &a; c= &b; ----------------------- void pointers ----------------------- Pointers that point to a value that has no type (and thus also an undetermined lenght and undetermined deference properties). .. code-block:: bash //increaser #include using namespace std; void increase(void* data, int psize) { if (psize == sizeof(char)) {char* pchar; pchar=(char*)data; ++(*pchar);} else if (psize == sizeof(int) ) {int* pint; pint=(int*)data; ++(*pint);} } int main() { char a= 'x'; int b=1602; increase (&a, sizeof(a)); increase (&b, sizeof(b)); cout << a << ", "<< b << endl; return 0; } ---------------------- Null pointer ---------------------- .. code-block:: bash int *p; p=0; --------------------------- Pointers to functions --------------------------- To pass a function as an argument to anoter functuion. you have to declare it as a protoype of the function except that the name of the function is enclosed betwen parentheses () and an asterix (*) is inserted before the name. .. code-block:: bash //pointers to functions #include using namespace std; int addition (int a, int b) {return (a+b);} int substraction(int a, int b) { return (a-b);} int operation(int x, int y, int(*functioncall)(int,int) { int g; g=(*functioncall)(x,y); return (g); } int main() { int m,n; int (*minus)(int,int)=substraction; m=operation(7,5, addition); n=operation(20, m, minus); cout<< n; return 0; } ======================== Dynamic memory ======================== ------------------------ Operators new and new[] ------------------------ pointer = new type pointer = new type [number of elements] .. code-block:: bash int *bobby; bobby = new int[5]; ------------------------------ Operators delete and delete[] ------------------------------ .. code-block:: bash delete pointer; delete [] pointer; The first deletes memory used for a single element. The second deletes memory used for arrays of elements. The argument passed to delete must be either a pointer toa memory block previously allocated with new, or a null pointer. .. code-block:: bash //rememb-o-matic #include #include using namespace std; int main() { int i,n; int *p; cout <>i; p=new (nonthrow) int[i]; if (p==0) cout << "Error: memory could not be allocated"; else { for (n=0; n>p[n]; } cout << "You have entered: " for (n=0; n #include #include struct movies_t { string title; int year; }; int main() { string mystr; movies_t amovie; movies_t * pmovie; pmovie = &amovie; cout << "Enter title: "; getline(cin,pmovie->title); cout << "Enter year: "; getline(cin, mystr); (stringstream) mystr>>pmovie->year cout<<"\nYou have entered:\n"; cout<< pmovie->title; cout<< "("<title Is equivalent to .. code-block:: bash (*pmovie).title +--------------+-----------------------------------------------+-------------------+ | Expresion | What is evaluated | | +==============+===============================================+===================+ | a.b | Member b of object a | | +--------------+-----------------------------------------------+-------------------+ | a->b | Member b of object pointed by a | (\*a).b | +--------------+-----------------------------------------------+-------------------+ | \*a.b | Value pointed by member b of object a | \*(a.b) | +--------------+-----------------------------------------------+-------------------+ -------------------------- Nesting structures -------------------------- .. code-block:: bash struct movies_t{ string title; int year; }; struct friends_t{ string name; string email; movie_t favorite_movie; } charlie, maria; friends_t *pfriends=&charlie; After the previous declaration we could use any of the following expressions: .. code-block:: bash charlie.name; maria.favorite_movie.title; charlie.favorite_movie.year; pfriends-> favorite_movie.year; ===================== Other data types ===================== ------------------------------- Defined data types (typedef) ------------------------------- typedef existing_type new_type_name; .. code-block:: bash typedef char C; typedef unsigned int WORD; typedef char * pchar; typedef char field[50]; We can use it in declaratios like: .. code-block:: bash C mychar, anotherchar, *ptcl; WORD myword; pChar ptc2; field name; ----------------- Unions ----------------- ------------------ Anonymous unions ------------------ ------------------ Enumeration ------------------ ======================= Classes (I) ======================= .. code-block:: bash class class_name { access_specifier_1; member1; access_specifier_2; member2; ....... } object names; Acces specifiers: private members of a class are accesible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. public members are accessible from anywhere where the object is visible. By default al members of a class declared with the class keyword have private acces for all its members. Therefore, any member that is declared before any other class specifier automatically has private access. i.e .. code-block:: bash //classes example #include using namespace std; class CRectangle { int x,y; public: void set_values (int, int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x=a; y=b; } int main () { Crectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } Operator scope of (::) Specifies the class to wich the member being declared belongs.