Cheat Sheet Prog

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Cheat Sheet.

1
Typed constant expressions Preprocessor definitions (#define)
const double pi = 3.1415926; #define PI 3.14159
const char tab = '\t'; #define NEWLINE '\n'

Statements and flow control


if (x == 100) if (x == 100) if (x > 0)
{ cout << "x is 100"; cout << "x is positive";
cout << "x is "; else else if (x < 0)
cout << x; cout << "x is not 100"; cout << "x is negative";
} else
cout << "x is 0";
Iteration statements (loops)
The while loop The do-while loop The for loop
int main () int main () int main ()
{ { {
int n = 10; string str; for (int n=10; n>0; n--) {
do { cout << n << ", ";
while (n>0) { cout << "Enter text: "; }
cout << n << ", "; getline (cin,str); cout << "liftoff!\n";
--n; cout << "You entered: " }
} << str << '\n';
} while (str !=
cout << "liftoff!\n"; "goodbye");
} }
Jump statements
The goto statement The break statement The continue statement
int main () int main () int main ()
{ { {
int n=10; for (int n=10; n>0; n--) for (int n=10; n>0; n--) {
mylabel: { if (n==5) continue;
cout << n << ", "; cout << n << ", "; cout << n << ", ";
n--; if (n==3) }
if (n>0) goto { cout << "liftoff!\n";
mylabel; cout << "countdown }
cout << "liftoff!\n"; aborted!"; OUTPUT:
} break; 10, 9, 8, 7, 6, 4, 3, 2, 1,
OUTPUT: } liftoff!
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, }
liftoff! }
OUTPUT:
10, 9, 8, 7, 6, 5, 4, 3,
countdown aborted!
Range-based for loop Another selection statement: if-else equivalent
switch.
int main () switch (x) { if (x == 1) {
{ case 1: cout << "x is 1";
string str {"Hello!"}; cout << "x is 1"; }
for (char c : str) break; else if (x == 2) {
{ case 2: cout << "x is 2";
cout<<"["<<c<<"]"; cout << "x is 2"; }
} break; else {
cout << '\n'; default: cout << "value of x
} cout << "value of x unknown";
OUTPUT: unknown"; }
[H][e][l][l][o][!] }
for (auto c : str)
cout << "[" << c <<
"]";
Cheat Sheet.2
Functions Return_type Function_name ( parameter1, parameter2, ...) { statements }

int addition (int a, int Functions with no type. The value description
b) use of void
{ void printmessage (void) 0 The program was
int r; { successful
r=a+b; cout << "I'm a The program was
return r; function!"; successful (same
} }
EXIT_SUCCESS as above).
This value is
int main () Arguments passed by value
defined in
{ and by reference header <cstdlib>.
int z;
void duplicate (int& a) The program
z = addition (5,3);
{ a*=2;} failed.
cout << "The result is
int main () EXIT_FAILURE This value is
" << z;
{ int x =7; defined in
}
OUTPUT: The result is 8
duplicate (x);cout <<x; } header <cstdlib>.
OUTPUT: 14

Default values in Declaring functions Recursivity


parameters
int divide (int a,int void odd (int x); long factorial (long a)
b=2) void even (int x); {
{ if (a > 1)
int r; r=a/b; int main() return (a * factorial
return (r); { (a-1));
} int i; else
int main () cin >> i; return 1;
{ odd (i); }
cout<<divide(12)<<'\n'; }
cout<<divide(20,4)<<'\n'; int main ()
} void odd (int x) {
{ long number = 9;
if ((x%2)!=0) cout << "It cout << number << "! = "
is odd.\n"; << factorial (number);
else even (x); return 0;
} }

void even (int x) OUTPUT: 9! = 362880


{
if ((x%2)==0) cout << "It
is even.\n";
else odd (x);
}

Overloaded functions Function templates


int operate (int a, int template <class T> int main () {
b) T sum (T a, T b) int i=5, j=6, k;
{ return (a*b);} { double f=2.0, g=0.5, h;
T result; k=sum<int>(i,j);
double operate (double a, result = a + b; h=sum<double>(f,g);
double b) return result; cout << k << '\n';
{ return (a/b);} } cout << h << '\n';
return 0;
int main () }
{ int x=5,y=2;
double n=5.0,m=2.0; OUTPUT:
cout<<operate(x,y<<'\n'; 11
2.5
cout<<operate(n,m)<<
'\n';}
Cheat Sheet.3
Namespaces
namespace myNamespace namespace foo int main () {
{ int a, b;} { cout << foo::value() <<
myNamespace::a int value() { return 5; } '\n';
myNamespace::b } cout << bar::value() <<
namespace bar '\n';
Namespaces can be split: Two segments of
a code can be declared in the same
{ cout << bar::pi << '\n';
namespace: const double pi = 3.1416; return 0;
namespace foo { int a; } double value(){return }
namespace bar { int b; } 2*pi; }
namespace foo { int c; } }

Initializing arrays
int foo [5] = { 16, 2, int bar [5] = { 10, 20, 30 int bar [5] = { };
77, 40, 12071 }; };

int foo [] = { 16, 2, 77, int foo[] { 10, 20, 30 };


40, 12071 };

Multidimensional arrays Arrays as parameters Character sequences


#define WIDTH 5 void printarray (int arg[], har myword[] = { 'H', 'e',
#define HEIGHT 3 int length) { 'l', 'l', 'o', '\0' };
for (int n=0; n<length;
int jimmy ++n) char myword[] = "Hello";
[HEIGHT][WIDTH]; cout << arg[n] << ' ';
int n,m; cout << '\n';
}
int main ()
{ int main ()
for (n=0; n<HEIGHT; {
n++) int firstarray[] = {5,
for (m=0; m<WIDTH; 10, 15};
m++) printarray (firstarray,3);
{
}
jimmy[n][m]=(n+1)*(m+1);
}
}
Pointers

myvar = 25;
foo = &myvar;
bar = myvar;

Dereference operator (*)


baz = *foo;
Cheat Sheet.4
Pointer (contd..)
baz = foo; // baz equal to foo (1776)
baz = *foo; // baz equal to value pointed to by foo(25)

• & is the address-of operator, and can be read simply as "address of"
• * is the dereference operator, and can be read as "value pointed to by"

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed to by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed to by p1 = 20

cout << "firstvalue is " << firstvalue << '\n';


cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
}
OUTPUT: firstvalue is 10
secondvalue is 20
Pointers and arrays Pointers and const Pointer arithmetics
int main () int x; char *mychar;
{ int y = 10; short *myshort;
int numbers[5]; const int * p = long *mylong;
int * p; &y;
p = numbers; *p = x = *p;// ok: ++mychar;
10; reading p ++myshort;
p++; *p = 20; *p = x;// error: ++mylong;
p = &numbers[2]; modifying p, which
*p = 30; is const-qualified
p = numbers + 3;
*p = 40;
p = numbers;
*(p+4) = 50;
for (int n=0; n<5;
n++)
cout <<
numbers[n] << ", ";
}
void increment_all (int* start, int* void print_all (const int* start, const
stop) int* stop)
{ { const int * current = start;
int * current = start; while (current != stop) {
while (current != stop) { cout << *current << '\n';
++(*current); // increment value ++current; // increment pointer
pointed }
++current; // increment pointer }
} int main ()
} { int numbers[] = {10,20,30};
increment_all (numbers,numbers+3);
print_all (numbers,numbers+3);
}
Cheat Sheet.5
Pointer (contd..)
Pointers and string literals
const char * foo = "hello";
*(foo+4)
foo[4]
Both expressions have a value
of 'o' (the fifth element of the
array).
Pointers to pointers
char a; b = &a;
char * b; c = &b;
char ** c;
a = 'z';
c is of type char** and a value void pointers
of 8092 The void type of pointer is a special type of pointer. In
*c is of type char* and a value C++, void represents the absence of type. Therefore, void pointers are
of 7230 pointers that point to a value that has no type (and thus also an
**c is of type char and a value undetermined length and undetermined dereferencing properties). This
of 'z' gives void pointers a great flexibility, by being able to point to any data
type, from an integer value or a float to a string of characters.
// increaser int main ()
#include <iostream> {
using namespace std; char a = 'x';
int b = 1602;
void increase (void* data, int psize) increase (&a,sizeof(a));
{ increase (&b,sizeof(b));
if ( psize == sizeof(char) ) cout << a << ", " << b << '\n';
{ char* pchar; pchar=(char*)data; return 0;
++(*pchar); } }
else if (psize == sizeof(int) ) OUTPUT: y, 1603
{ int* pint; pint=(int*)data; ++(*pint); }
}
Invalid pointers int * p // uninitialized pointer (local variable)
int myarray[10];
int * q = myarray+20; // element out of bounds
null pointers int * p = 0; int * r = NULL;
int * q = nullptr;
Do not confuse null pointers with void pointers! A null pointer is a value that any pointer can take to represent
that it is pointing to "nowhere", while a void pointer is a type of pointer that can point to somewhere without a
specific type. One refers to the value stored in the pointer, and the other to the type of data it points to.
Pointers to functions int main ()
int addition (int a, int b) { int m,n;
{ return (a+b); } int (*minus)(int,int) = subtraction;

int subtraction (int a, int b) m = operation (7, 5, addition);


{ return (a-b); } n = operation (20, m, minus);
cout <<n;
int operation (int x, int y, int return 0;
(*functocall)(int,int)) }
{ In the example above, minus is a pointer to a function that has
int g; two parameters of type int. It is directly initialized to point to
g = (*functocall)(x,y); the function subtraction:
return (g); int (* minus)(int,int) = subtraction;
}
Cheat Sheet.6
Pointer (contd..)
Cheat Sheet.7
Classes class Rectangle {
class class_name { int width, height;
access_specifier_1: public:
member1; void set_values (int,int);
access_specifier_2: int area() {return width*height;}
member2; };
...
} object_names; void Rectangle::set_values (int x, int y) {
width = x;
height = y;
class Rectangle { }
int width, height;
public: int main () {
void set_values (int,int); Rectangle rect;
int area (void); rect.set_values (3,4);
} rect; cout << "area: " << rect.area();
return 0;
}
OUTPUT: area: 12
Constructors Rectangle::Rectangle (int a, int b) {
class Rectangle { width = a;
int width, height; height = b;
public: }
Rectangle (int,int);
int area () {return int main () {
(width*height);} Rectangle rect (3,4);
}; Rectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
}
Overloading constructors Rectangle::Rectangle (int a, int b) {
class Rectangle { width = a;
int width, height; height = b;}
public: int main () {
Rectangle (); Rectangle rect (3,4);
Rectangle (int,int); Rectangle rectb;
int area (void) {return cout << "rect area: " << rect.area() << endl;
(width*height);} cout << "rectb area: " << rectb.area() << endl;
}; }
Rectangle rectb; // ok, default constructor
Rectangle::Rectangle () { called
width = 5; Rectangle rectc(); // oops, default constructor
height = 5; } NOT called
Uniform initialization Circle foo (10.0); // functional form
Circle bar = 20.0; // assignment init.
Circle baz {30.0}; // uniform init.
Circle qux = {40.0}; // POD-like
Pointers to classes int main() {
class Rectangle { Rectangle obj (3, 4);
int width, height; Rectangle * foo, * bar, * baz;
public: foo = &obj;
Rectangle(int x, int y) : bar = new Rectangle (5, 6);
width(x), height(y) {} baz = new Rectangle[2] { {2,5}, {3,6} };
int area(void) { return cout << "obj's area: " << obj.area() << '\n';
width * height; } cout << "*foo's area: " << foo->area() << '\n';
}; cout << "*bar's area: " << bar->area() << '\n';
cout << "baz[0]'s area:"<< baz[0].area()<<'\n';
cout << "baz[1]'s area:"<< baz[1].area()<<'\n';
delete bar; delete[] baz; return 0;}
Cheat Sheet.8 Classes(contd..)
expression can be read as
*x pointed to by x
&x address of x
x.y member y of object x
x->y member y of object pointed to by x
(*x).y member y of object pointed to by x (equivalent to the previous one)
x[0] first object pointed to by x
x[1] second object pointed to by x
x[n] (n+1)th object pointed to by x

(I)

http://courses.cs.vt.edu/~cs2605/spring08/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy