C++ Reference Guide


This guide assumes you know some very basic C++ ideas...anything of that nature can be referenced quickly in any intro C++ book.

For Loops

// Compare at top, Update at end
for (initialization; comparison; update)
{}


for (int i=1; i<=10; i++)
{
    cout << i << endl;
}

int i; // New ANSI standard
for (i=1; i<=10; i++)
{
    cout << i << endl;
}


Do Loops

do {
    } while (condition);
//Always executed one time at least


int x = 1;
do {
    cout << x;
    x++;
    } while (x <= 9);


While Loops

while (condition) {
    }

int x = 1;
while (x <= 10) {
    cout << x << endl;
    x++;
    }


Functions

return_type name(arguments) {
    statements;
    return (appropriate type);
}

int add_one (int num)
{
    num++;
    return num;
}


Enumerated types

enum boolean{FALSE, TRUE}; //FALSE=0, TRUE=1


Switch

switch (control_expression) { //int, char, bool, enum - example is int
    case 1 : {statements;} break;
    case 2 : {statements;} break;
    ...
    default : {statements} break;
    }


Strings

typedef char name[size];


name name2[size2]; // name2 is an array of size2 strings of length size

-Using the built in library

	#include <string.h>
	strcpy (x,y);			// Copies y into x
	strlen(x);			// Returns length of x
	strcat(x,y);			// Puts y on x and adds '\0'
	strcmp(x,y);			// Compares x to y
   					// If x == y, returns 0, x < y, returns -int
   					// x > y, returns +int
	cin.ignore(80,'\n');		// Flushes buffer...used after reading 
					// numeric data to get rid of newline 
	cin.getline(str,50,'\n');	// Gets up to 50 chars until '\n' is 
					// encountered and stores them in str


Files

#include <fstream.h> // Must include this library
ifstream fin("name.txt"); // Opens in-file and ties it to fin

ifstream fin; // These 2 lines do the
fin.open(filename); // Same as above

if (!filename) {} // If there's a problem with file

fin.close(); // Closes file
fin.clear(); // Clears fin, similar to cin.clear()

ofstream fout(filename); // Opens out-file named filename and ties it to fout

fout.close(); // Closes output file


Arrays

type name[size]; // Creates array with elements 0..size-1


Size is the maximum size and must be known at complie time.

int a[]={1,5,7,3}; // Array size is 4
int b[10]={1,7,3}; // b[0], b[1], b[2]. b[3]...b[9]=0

-In a function definition

       void f(int a[])

-In a function declaration

       void f(int a[], int[], int* a);

-In a function call

       int num[50];
       f(num); // Always passed by reference by default

-Passing as const

       float f(const int num[]) // Can't change...may be const int& num[]

Multi-dimensional Arrays

type name[ROWS][COLS];

-Passing, or in a function

       int f(int x [] [size] [size2]); //Must give it all but first dimension


Structs

struct name {
   char itemName[25];
   int instock;
   };
// Could be }item1={"Hammer",7};

You can have as many data items in a struct as you want.

name items[10]; // Array of structs
items[1]=items[0]; // Can use = for entire struct
items[0].instock=4;
strcpy(items[0].itemName, "Hammer");


Bubble Sort

//You WILL need this code at some point!!

void Bubble_Sort(int a[], int size)
{
   int temp;
   for (int pass=1; pass<size; pass++)
      for (int i=0; i<size-1; i++)
         if (a[i]>a[i+1]) {
            temp=a[i];
            a[i]=a[i+1];
            a[i+1]=temp;
         }
}


Common Errors & Tips

Make sure you're passing in the right number and kind of arguments. Try to use structs if you have large groups of data.

Remember, the arrows point to where the data will go!!

This is 0!! Much harder to spot in something like a/b where both are ints! When in doubt, use something like float(a)/b.

Not sure what this does? Break it into 2 statements : y=x; x =x + 1;

Everyone does this at some time when they really want to compare. Remember = is for assignment and == is for comparison. I guarantee this will show up on a test in some form or another!

couts are your friend...if your data's not coming out right, cout it to the screen as soon as you read it in. Often, cout is better than any debugging program!

You'll get enough of these in 210! In 114, usually means something's wrong with your array assignments or something similar.

This is probably the hardest one you'll encounter. It usually comes from making a prototype, calling the function, and either not defining it, or defining it wrong. Look at the prototype and the actual definition to make sure their names and arguments match.

Remember you don't put the []'s when doing a function call! They are used in the definition and prototypes!

Compilers aren't perfect! Sometimes the line number may be off by 1 or 2...check the surrounding code.

Don't do this! Use the space you need to match up brackets and make your code easy to read. Comment closing brackets!

Ouch! You just erased your program! I've seen this happen, and it's not pretty. -o means to call the executable whatever's next. If you call your program it's own name, it will over write it.

Ok, I never did this either, but it would make life easier...

It will probably bump you up a letter grade if you do. Also, 114 is the base of a triangle...you gotta know this stuff to go up!

Ok, you've traced it down to one function, and everything looks right, but your variable is picking up some weird value. Check and see if you've defined a variable without setting it...if you have, set it to some initial value. Not all compilers blank variables when they're defined!

© Copyright 1997 Alan Watkins