C++ Cheat Sheet and Quick Reference Guide

The Tools

To compile and test code on Windows, my recommendation would be using:
Microsoft Visual Studio 2008/2010 Express Editions (ask your instructor about full versions)

On an older Windows box (if it’s not quad core), you might want to use Visual Studio 2008 instead of 2010. 2010 is excellent but much more performance intensive, although there are some automation patches and other service packs that do help performance, start up still seems to be a little slow – kind of like me getting up in the morning after 3-day redbull-coding hyperdrive. 😀

Adding “/nosplash” on your launch shortcut helps speed up launch time alot on my PC as well.
Right Click on Shortcut->Properties->Replace Target with: “C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe” \nosplash

If you’re on Linux or other systems, you could use gcc which comes with your distro out right out of the box. However, since gcc is CLI, you might want to use Eclipse or Mono instead.

Don’t try to write this on the palm of your hand..

(See Matt Mahoney’s reference at bottom of page for more complete reference).

//this is a comment
spans multiple 
lines */

#include <stdio.h> //generic standard files (you don't create these)
#include "otherclass.h" //files in your project in current directory (you do create these)

//these are examples of defining your own custom literal constants 
#define PI 3.1415
#define NEWLINE '\n'

//similar to normal conditional logic, but fires BEFORE compilation so allows for some different things
#if defined(value) //same as #ifdef value
//do something

//these are the building blocks of your more complex types. every class, type or object can be broken down in simplest form to these types
unsigned int
signed int
String //sometimes represented with lowercase s instead of capital. this is technically not a base value type in C++, but is generally accepted as one in many languages... since it's not a base value type it requires include <string.h> to use

//these are commonly allowed expressions
255 //integer 
0377 //octal, preceded by 0
0xAF //hexadecimal, preceded by 0x
2000000000L //Long (32bit) integer, notice it ends with L
0x0fffffffl  //same applies to hex, notice it ends with L which is not part of hex
123.0 //known as a double
1.23e2 //also allowed
'a', '\141', '\x61' //characters
'\n', '\\', '\'', '\"' //newline, backslash, single quote, double quote
"hello world"                //a powerful force known as the "string", which is actually an array of characters
"hello" "world" //concatenated strings
true, false //boolean values, also represented by integers 1 and 0

int x; //declare an integer, notice it starts with "int" and followed by variable name
int x=1; //when declaring can also specify an initial value
short y; long z; //short is 16 bit int, long is 32 bit int. this affects the max value it can be, such as 255
unsigned int largenum=52625; signed int negnum=-1;  //declaring unsigned or signed allows for larger numbers and negative values. if not specified defaults to signed
unsigned long x=0xffffffffL; //same applies to octal, hex
float f=1.00; double d; //cannot declare unsigned. float is for numbers with many decimal places, double is big numbers
bool cool=true; bool cool=1; //boolean true or false, 1 or 0 value
int x, y, z; //multiple declarations can be declared in one line
char initial='r'; //8 bit single character. may not used commonly by itself, but important for arrays

//even though if may not seem logical at first, for consistency purposes, remember your arrays always start at index 0 not index 1. you can workaround this by never setting value at index 0, but I wouldn't advise it since programmers rarely ever start with 1
int numberarr[5]; //declare an array. in this example this is equivalent of {0,0,0,0,0} stored in memory
int one_d_numberarr[]={0,1,2}; //initial values can also be specified for arrays. note that array size is not specified here but initial values are
int two_d_matrix[4][4]={{1,2,3,4},{5,6,7,8}};  //arrays can have multiple dimensions with different sizes, also allowing for initial values
char message[]="hello"; //array of characters, more commonly known as a string
string message = "hello"; //simpler and more common declaration if you include <string.h> or System::String in namespace System on Windows

//pointers are not prevalent in all programming languages, and not always necessary to create your application but usually will improve performance.. as well as complexity....
int* p; //declares a variable which
char* message="hello";
int& newvalue=oldvalue; //creates a reference to original value, so both share and reuse the same space in memory

//an enum is a simple type. see examples below
enum weekday {MON,TUE,WED,THUR,FRI};   //any variable declared with a type of weekday will strictly contain one of these variables
enum weekday day; //declare a variable where it's type is weekday instead of a base value type
enum weekday {MON=0,TUE=1,WED=2,THUR=3,FRI,=4};  //here the values are declared explicitly, which might be useful in some cases but is generally assumed from order of values
enum {MON,TUE,WED,THUR,FRI} day; //here the variable is declared without specifying a type name of weekday. this is known as an anonymous declaration
typedef String char*; //declaring "String message" would now be equivalent to "char* message"
const int commonmultiplier=2; //constants must be initialized. this effectively declares a read only variable which cannot be modified after its declaration. constants can also be used in conjunction with pointers for some interesting effects

int x; //variables declared simply like this are automatically allocated to memory while you are within the function they are declared then cleared afterwards
static int x; //variables declared with static persist in memory, even outside of current function
extern int x; //variables declared extern exist outside of current function

x=y; //simplest statement ever
int x; //a statement is basically anything ending in ; or between { }

{                         //once you open a bracket, anything inside, unless static or extern only exists within those brackets
  int y; //even though this value is not accessible outside of this block, if it is within the same function the same variable name cannot be used

if (x) somefunc();                 //if x is true or not 0 then do func
else if (y) someotherfunc();            //optional if you want to specify an else if statement
else if (z) unexpectedfunc(); //multiple else if's can be declared
else exitstrategy();                   //also optional if you want to specify an else statement, but if you're sure that your if statement will always be executed, then ask yourself why you are using if at all

 //equivalent to the above, in a more explicit format which I recommend getting used to. it is longer but easier to read and better formatted. if you like the above better, go learn python instead!
if (x) {
else if (y) {
else if (z) {
else {

while (x) somefunc();              //execution does not fire unless condition is met and continues in an indefinite loop until condition is no longer true
while (x) {

for (int x=0; y<=x; x++) somefunc;          //this is my favorite loop logic since x is disposed of when loop is done. this is roughly equivalent to "int x =0; while(y<=x) {somefunc(); x++;}"
for (int x=0; y<=x; x++) {

do somefunc(); while (y<=x);          //similar to while, except execution fires at least once even if condition is not met, then continues indefinitely until no longer true. this might be useful for executing a process that should only execute once, but due to some unknown factor, may need to try multiple attempts to execute in case the first one does not take effect
bool executed = false;
do {
executed = somefunc();
while (executed!=true);

//x must always be a number in a switch, enums represent numbers so these work too
switch (day) {
  case weekday.MON: mondayfunc(); //case values must be constants
  case weekday.FRI : tuesdayfunc(); //each case is evaluated until a match is met
  default: weekdayfunc();

break; //exit a while,do,for loops or switch
continue; //skip any following logic in the loop and go to next interation
return x;  //breaks a loop or exits a function with return value

//basic exception handling. extremely important to every application
mainfunc() {
try { somefunc(); }
catch (T t) { fixfunc(); mainfunc(); }        //if exception thrown is something expected and you encountered before, handle for it
catch (...) { emailerror(); }        //if something unexpected, which is the usual case

//ahh the good stuff
//functions must be preceded by a type, this is there return value. if no type is specified, they default to int
bool somefunc();
int someotherfunc();
someotherfunc(); //this works too and defaults to int, though being explicit is always recommended
void unexpectedfunc(); //if functions do not have a return value, then they are declared as void
bool somefunc(int x, int y); //functions may have a virtually unlimited number of parameters
//the function can be declared somewhere else, then used later. this is useful structurally and helps you stay organized such as by created a .h (header) file for every class and defining functions here, then include the file in your class, then simply use the functions
bool somefunc(int x, int y) {dosomething(x,y);} //or for rapid development it can be done in one shot
bool somefunc(int x) {dosomethingelse(x,0);} //a function with the same name and different parameters can be declared more than once. this is called overloading functions
inline f() //inline is optimized for performance

//standard operators can also be overloaded and declared for specific types
weekday operator+(weekday x, weekday y) { notifyuserofinvalidoperation();} //when adding two days, will execute custom functionality
weekday operator-(weekday x) {notifyuserofinvalidoperation();} // can do the same if you tried to do -day
weekday operator++(int) {notifyuserofinvalidoperation();} //same for ++

extern "elsewhere" {void func();}    //declare a function declared elsewhere

//a class is how you define your own type. base value types like int and char are already defined for you, and some other types like enum or String are either already included in the language or part of your compiler/IDE.
//classes are usually called "reference types"
class MyClass {
private: //any variables or functions declared here are only accessible from within the class
int x;
protected: //variables or functions declared here are accessible from within the class and to classes derived from T
void func();
public: //accessible to all. this is easiest to use when learning, but keep in mind, like the public pool, this is not always best 🙂
int operator+(int y);   //custom operator for adding your class to an integer

//subclass of your original class. note it is not automatically initialized when a variable of your class type is declared new
class SubClass {

T() {} // (optional) known as a constructor, this function is called when the object is declared new
~T() {} // (optional) known as a destructor, this function is called when the object is destroyed

explicit x(int n); //allow you to do O1.x=O2.x but now O1.x=3 (O1 and O2 are objects of your class type)

friend void G_f(); //allow global function f() to access your private members
friend class G_U(); //allows members of class U to access your private members

static int x; //each instance of an object of this class type will all have the same value for x
static void v(); //can call this function externally if accessible even if object not instantiated

virtual //if declared virtual then function or member is essentially just a placeholder, meaning other classes will inherit this class and define the same function and can override it

//a variable of your defined type which is created and destroyed in code is known as an OBJECT instance
//the creation process (declaring new in C++) is known as "object initialization" or just simply "instantiation"
MyClass ClassObj = new MyClass(); //note I can pass in params here if they're defined in constructor. ClassObj is now reference to an object instance of MyClass
MyClass OtherObj = new MyClass(); //this would be a second object instance of the same class
delete ClassObj; //will call destructor if it's declared
OtherObj::f(); //will call function f() defined in class

class SuperClass: public MyClass {};     //SuperClass is now a derived class of the base class MyClass, and inherits all public members
class SuperClass: private MyClass {};    //same as above, but inherited members in SuperClass which were public in base class are now private
class SuperClass: public MyClass, public OtherClass {};  //new class can inherit from multiple classes
class CloneClass: public virtual MyClass {}; //essentially clones MyClass. instead of CloneClass having a base class of MyClass, both CloneClass and MyClass will have the same base class that MyClass has

//most of these you probably inferred by now by reading through above
x++; x--; //add or subtract 1 from itself. equivalent to x=x+1 or x=x-1;

arrayname[i]; //get value in array at index

ClassName::Objectname //should look familiar from System::String earlier. this is explicit syntax when declaring an object defined in different class
NamespaceName::X //same applies for namespaces
::X //global

classname.membername //access function or variable in initialized class
pointername->membername //access function or variable pointed to by pointername

typeid(x); //get type of x
(int)x; ///implicit conversion of x to an integer.
dynamic_cast<T>(x) //performs conversion and checks it when the application is run
static_cast<T>(x) //performs conversion and does not check it
reinterpret_cast<T>(x) //bit conversion
const_cast<T>(x) //performs conversion and remaining variable is type without constant

sizeof(x) //size in bytes of object
sizeof(T) //size in bytes of type

new T //returns address of newly created T
new T(x, y) //returns address of newly created T, contains parameters
new T[x] //address of newly allocated T define in array
delete p_addr //destroy object and free resources which was earlier declared new at address
delete[] p_addr //destroy array of objects stored at address

x * y //multiply
x / y //divide, rounded down
x % y //modulus, divides x and y and returns the remainder
x + y //add, different functionality with pointers
x - y //substract, different functionality with pointers
x << y // x shifted y bits to left
x >> y // x shifted y bits to right
x < y //x is less than, returns bool
x <= y //x is less than, returns bool
x > y //x is greater than, returns bool
x >= y //x is greater than or equal to y, returns bool
x == y //equals, returns bool
x != y //not equal, returns bool
x & y //bitwise and
x ^ y //bitwise exclusive or
x | y //bitwise or
x && y //x and y (doesn't get to y if x is false)
((1==1) && (2==2)) //example of above syntax
x || y //x or y (doesn't get to y if x is false)
((1==1)||(2==2)) //example of above syntax
x = y //assign value in y to x
x += y //x = x + y
-= *= /= <<= >>= &= |= ^= //same as above

x ? y : z;                 // return y if x is true (nonzero), else return z
(1==1) ? dosomething() : dosomethingelse(); //example of above

throw x; //throw an exception. if not caught within try catch will probably exit application

x , y //evalutates x and y and returns y
int returnvalue = dosomething, dosomethingthatreturns();

~x //bitwise complement of x
!x //returns opposite of x, if x is true, returns false. if x is 1, returns 0.
-x //unary minus
+x //unary plus
&x //address of x (used in conjunction with pointers)
*p // value pointed to by address p (*&x equals x)

Hello World

A namespace is basically exactly what it’s called. The name which you used to identify your application from code, which wraps all your classes and occupies a defined “space” on your computer/in memory.

//So basically when you see:
using namespace System;
//or on non Windows machines
using namespace std;
//this is saving you from having to write out System::SomeClass or std::SomeFunction

The information in the above cheat sheet is useful, but you’ll need to reference other code to actually make some magic. This is where namespaces come in. See example below for basic “hello world” app which uses standard namespaces to write output to your console.


#include <iostream.h>
#include <stdio.h>

using namespace std;
int main() {
cout << "Hello World"; //write to console window
char* s;
cin >> s; //pause for input key so you can actually see what was written
return 0;


using namespace System;
int main(array<System::String ^> ^args)
Console::WriteLine("Hello World"); //technically not an output stream, but essentially does the same thing as cout
Console::ReadLine(); //approximately the same as cin
return 0;

A few things were not covered, such as pointers, using typedef in classes, overloading and overriding functions and common string operations as well as other notable “common” operations defined in standard namespaces. Hopefully this will help serve as a quick reference to you in the future if you decide to learn more or take a break for awhile and need to quickly brush up.

Sourcepole (Matt Mahoney), http://www.sourcepole.com/sources/programming/cpp/cppqref.html
Cplusplus.com, http://www.cplusplus.com/doc/tutorial/constants/
MSDN (Visual Studio Express), http://www.microsoft.com/express/Downloads/
Eclipse (C/C++ page), http://www.eclipse.org/downloads/moreinfo/c.php
Mono, http://www.mono-project.com/Main_Page
(MSDN) Windows Automation API 3.0, http://support.microsoft.com/kb/981741
Visual Studio “nosplash” startup speed, http://geekswithblogs.net/MikeParks/archive/2010/05/12/visual-studio-2010—faster-startup.aspx


About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on May 6, 2011, in Language References, Programming & Development and tagged , , , , , , , , , , . Bookmark the permalink. 2 Comments.

  1. Good comment Tomato. This page serves as more of a quick reference, but the explanation on your blog utilizing pointers/delegates to achieve the functionality you described is accurate and useful.

  1. Pingback: Tomato Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: