VC's Breakneck C++ Tutorial! You're here because you want to learn to program and you know little or nothing about how. I'm here to teach you everything you need to know to get started in short order. This is going to be a pure HTML plain-text affair. By The Way, when I captialise a series of words, expect I will abbreviate them thereafter.

One more thing, I'm weird and I indent the closing brace on blocks of code. That changes nothing, but it looks a little different from 98% of C++ code. If your IDE has a highlight-braces-pairs feature, it will be your salvation. (DevCPP has it in one of the options pages.)

• Get Your Toolkit

Choose an Integrated Development Environment. For Windows, DevCPP and Codeblocks are good IDEs. You can get Microsoft's Express components, but aside from modding Source engine, I can't think of any reason why you should. On Linux, KDev and Codeblocks work. If you choose DevCPP for Windows, get wxDevCPP if you have any interest in making conventional applications. In fact, just get wxDevCPP -- Bloodshed hasn't kept it updated, while wxDevCPP is a Work In Progress.

• Your First Program

Hello World is dumb. We're going to have fun instead. I'm writing from DevCPP's perspective, so your editor may have different templates.

1) Start your Engine

Search your IDE's menu for a new project creation command. Select Console. After zero to many popups, you'll see code like this:

#include <cstdlib>
#include <iostream>
using namespace std;

int main(int argc, char *argv[]){
  system("PAUSE");
  return EXIT_SUCCESS;
  }

NOTES:

#include statements list what libraries we want to use. Libraries are bits of code that we will use so we don't spend all day re-inventing the wheel. DLL stands for Dynamic Link Library, so you've seen this before. Some libraries compile into the EXE, others are DLLs that stand next to the EXE. You'll learn the important ones in time. Right now we have the C Standard Library (good stuff) and Input/Output Stream (gives us power to use keyboard and put text on screen).

using namespace tells the compiler we are lazy. Most/All the functions in the CSL are std::functionname. using namespace std; tells the compiler to add std:: to function names it can't find because we aren't going to bother to type them.

system("PAUSE") will pause the program so we can see our box. Non-interactive programs will open, finish, and close faster than Windows draws the box, so you need this for now. Ditch it when you go pro, system() is bad form, and doesn't necessarily work across platforms.

This is our do-nothing starting point. So let's do something.

2) Zardoz Speaks to You: "Print the numbers One through Ten!"

No problem. We need only three things to do this. We need a number to count with, a way to display it, and a way to do it ten times. This codes itself.

int main(int argc, char *argv[]){
  long ix = 1;
  while(ix < 11){
    cout << ix << '\n';
    ix++;
    }
  system("PAUSE");
  return EXIT_SUCCESS;
  }

As you can see I omitted the #includes. To keep this focused, I only include what's changing and enough for context. Don't remove your #includes or you will not proceed.

NOTES:

The first thing we do is create a variable. long is one of a dozen basic types of numbers. long gives us a range of ±2.1 billion, which is plenty. Use float if you need decimals, because long is an integer type, and truncates away any decimals. (That means 19 / 10 = 1 in integer land) Here we've both declared (told the compiler we need a variable) and defined (given a value to) the variable. Get in a habit of this. If you don't define it and use it anyway, the variable will have an arbitrary* value in it, and you have lost control of your program. I use "ix" for short-lived iteration loops, you can call variables almost whatever you want, but keep them simple and descriptive, or you'll confuse yourself eventually. (*When I say arbitrary, I mean you don't know what you get -- usually Zero, often Something Else. I'd say "random" but someone with nothing better to do will gripe about how it isn't truly random in the quantum-mechanical sense.)

cout is a CSL function for putting stuff on the screen. We can feed it just about anything. The << operators work like arrows showing where stuff is going. This is a very strange syntax, so don't go expecting angle brackets to be much use elsewhere.

while is our first flow-control device. The way it works is simple -- while looks at the expression next to it, in this case (ix < 11), and if ix is less than 11, it does everything within the following { } block. At the end, it checks the expression again. If it's still true, it jumps back and runs the block again. If not, execution continues. ++ is a shortcut for "add one to this." ix += 1; would work, also, as += means "add that to this."

We've created a variable, set it to 1, and put it in a loop. Print the value (1), increment it (1+1=2), if it's less than 11, repeat. Eventually it will print 10, add one, see that 11 is not less than 11, and the loop ends. BTW, that '\n' says to start a new line on screen. Without it, the output would be "12345678910Press any key to continue. . ."

3) for the horde!

The for(;;) command is a special while(). It's more straight-forward for loops like ours. Here's the same thing in for(;;) form.

for(long ix = 1; ix < 11; ++ix)
  cout << ix << '\n';
NOTES: The for(;;) command combines a variable dec/def, a test expression, and a command normally used for incrementing into one line. You can make more than one variable this way, and do exotic things in the incrementer if you like, like this: for(long a = 1, b = 3, c = 100; a * b < c - a; a += (c / b) );. Also notice I didn't use the braces. Many commands will allow you to omit the braces if you would be enclosing a single command. Use the braces all the time if it helps you keep things straight, but I prefer to leave them off.

4) Homework Assignment.

So far you've learned how to make a variable, set and modify its value, print it to the screen, and enclose code you want to repeat a certain number of times. Now, you're going to build on this program thus:

• Using the while() loop example, use += 2 to print even numbers: 0 2 4 6 8 (...) 20. Be sure 0 prints first, and 20 is last. Also, put them on one line by removing the \n newline command and using a string that contains a single space: " "

• += isn't the only apply-to-self operator. Use *= 2 and you can double the number each time. Start with 1 and print the binary sequence up to 2147483648. (Something interesting will happen after 1073741824, here's your hint, use while( ix ) as your expression. That should be an infinite loop since ix is never going to be Zero, but...)

• Play with it. You can make a bunch of variables and loops, now. You can print arithmetic sequences, geometrics, Fibbanacci, (crude) multiplication tables. Go nuts.

5) "JANE! Stop this crazy thing!"

Playing with loops and being a newb, you're probably going to create an infinite loop sooner or later. Most IDEs will let you kill the process with a big red button, and direct program shutting methods usually work. If you're on a terminal, you can usually use Control C (^C, yeah, the "copy" command) to kill a terminal process. Terminal apps in Windows at least are good about being ^C killable, but when you get into proper Windows, you won't have this luxury, and will be resorting to Task manager if you trap yourself in a loop, assuming your IDE can't shoot it down for you.

6) 2^32 = 0

Integers are stored as binary numbers. If you don't know what they are, go visit Wikipedia. The above homework assignment demonstrates the importance of considering the range of your integer variables. Each time we multiplied the value by 2, we effecitvely bit-shifted the value in memory to the left. So, 1 became 10, became 100. Since we were using a signed long integer, when 1000000000000000000000000000000 became 10000000000000000000000000000000, it no longer represented a positive number, because the 32nd bit represents the sign of the number. The final time we doubled the value, the 1 bit was pushed out of the value completely, leaving nothing but 0's.

As a side note, you can use the bit-shift operators, << and >>, to peform this behavior, and thus, muliply or divide by a power of two. Normally, this is considered bad behavior with normal math, but good behavior when working with colour channels, since they are represnted with octets packed into unsigned long integers.

7) Decisions, Decisions.

Without the ability to take two paths based on a condition, the program isn't able to express any variation in behavior. We used an expression to control our loops, but that isn't so much decision making as waiting around for something to happen.

The most intuitive flow control system is the if, else block. The expression is resolved, and if the value is anything other than ZERO, the line or block following the if is exectued. If the expression is zero, the program jumps to the end of that line/block and continues execution. If the expression was true, when that line/block ends, if there is an else, execution jumps over it.

if( health == 100 )
  lifecolor = 0xFFFFFFFF; // 0xDIGITS lets you specify in base-16 hexadecimal numbers. Wiki it.
else if( health > 50 )
  lifecolor = 0xFF88FFFF; // Colors are almost always specified like this.
else
  lifecolor = 0xFF2244FF;

Note there are no ; after if or else. Like with the loops, you must make blocks when more than one line is dependent on the if/else. if( time < 10 ) { ; ; ; } else { ; ; ; }.

There are two more kinds of conditionals we should look at. One, is the ternary operator, ?:. Use this when you have a simple decision to make that controls a value. For example, score += ( level > 5 ) ? 500 : 200;. If level is greater than five, 500 is added to score. Otherwise, 200 is added. And yes, you can nest these bad boys and make your code damn near unreadable. This is useful for small expressions and takes less space than writing out a full if/else block.

The other conditional is a very special one, switch. Switch is a bizzare shorthand for if( variable == number ) blocks. You'll use it when one variable is representing states.

// Assume we have two longs, a and b, which the user entered already.
long opera = 0;
cout << "Choose an operation: 1) +, 2) -, 3) x, 4) /\n"
cin >> opera;
switch( opera ){
  case 1:
    a += b;
    break;
  case 2:
    a -= b;
    break;
  case 3:
    a *= b;
    break;
  case 4:
    a /= b;
    break;
  default:
    cout << "You did not choose a valid option.\n";
  }
cout << "Result: " << a;
In a switch block, execution jumps to the case statement that has the same value of the operator, and runs. If it can't find a matching case, it jumps to default, if you provided one. Note the : at the ends of the case lines, these are really goto labels. Also note you can stack them, case 5: case 6: case 7: to make muliple values go to the same place, and you cannot use expressions or variables or ranges as case targets. Also, note the use of break;. Break makes execution jump out of the switch block. Execution will run through case satements. This is good if you want, for example, case 2 to do something then do what case 1 does... just put 2 above 1 and don't add a break.

DANGER! DEATHRAY! If you've used = as the comparison/equality operator, expect to use it inapropriately. If you use something like if( x = 3 ), you will set x to 3, and then the if statement will always throw true because x isn't zero. This will not only cause your if-block code to behave like an idiot, but can make really weird things happen if x is used later. BTW, if you see code where the comparisons are reversed for some reason, e.g., 3 == x, the some reason is because 3 = x will throw a compiler error, since you can't assign x to 3, which catches the =/== programmer's error.

8) "I am fully functional, and programmed in multiple techniques."

Functions are the way we organise code and prevent ourselves from ever needing to write the same code multiple times. That's a little test of your programming skill -- every time you copy-paste some code, you should've made it a function. My personal rule is to make a function out of anything I need in three locations. Two is okay if it's justified, but beyond that it's sloppy and if you change one copy of it you're going to miss one of the others and wonder why your code is crapping out.

A function is, effectively, two things. A variable that has no real scope (it only exists in the line you use it in) and a block of code that gives that variable a value.

WARNABROTHA! Your compiler will irritate you to no end until you learn how to make proper functions. Pay close attention to what I say in this section.

Let's re-invent the wheel and write a function that adds two numbers.

long mathADD( long a, long b ){
  long c = a + b;
  return c;
  }
Now, in my code, anywhere I could put a long (because my function's return type, to the left of the function name, is long) I can put mathADD. Thus, I can say long d = 7 << mathADD(1, 2); or long e = mathADD( 1, mathADD(2, 3) ); and it'll work fine. Whenever the compiler sees mathADD it's going to run the function code and the returned value is the value of mathADD() in the expression.

IMPORTANT: The arguments in the function are newly declared variables that are defined with the values you put in the function call. Thus,

long doubleval( long a ){
  a *= 2;
  return a;
  }
int main(,){
  long x = 3;
  cout << doubleval(x) << '\n';
  cout << x << '\n';
  }
... is going to print 6, 3, because doubleval returned a*2, but I only sent x's value of 3 to the function, x itself was not changed. If you want your function to manipulate a variable you send it (and thus you could not send it a literal value like '3') you must make a reference like this: long doubleval(long& a){}. This is the C++ way. C allowed for pointers, which we'll abuse the hell out of later.

IMPORTANT: The compiler must know what your function looks like, even if it doesn't know what it does, before you use it. Note that I put doubleval before main in the above example. If I didn't, the compiler would whine about not knowing what doubleval is. If you want to put the code elsewhere, you must prototype the function, by telling it what it looks like. For example, long doubleval(long); before main, and the actual function in its gruesome entirety after main. In real programs, you'll make a header file (code comes in pairs, so you'd have codefile.cpp and codefile.h) that contains your prototypes so you can put your code wherever you like. Also, you will use #include in one code file (or code file's header) so the compiler knows what functions from other code files look like.

9) Yo Noid! ...er...void!

There is a special type that you now need to know about. void has two major uses. The first is to make a function that doesn't return a value. Obviously, that means a void function can't be where a number normally would go, and you would use return; instead of return varname; since you can't return anything. There is zero harm in using a function with a return type as though it were void, and often you want to return something so you can catch bugs. For example, a let's make a function that looks to see if a file exists.

long dir(string& path){
  FILE * fp = fopen(path.c_str(),"rb");
  long filefound = (fp)? 1 : 0
  if(fp) fclose(fp);
  return filefound;
  }
This function receives a string object (we'll look at them later), tries to create a pointer to a file stream (we'll look at them and them later), closes the file if it existed, and then returns 1 if the file existed, and 0 if it didn't. Now we can test for a file with something like if( dir(filename) ) { // code if file found } else { cout << "File not found.\n"; } Obviously that is the only functionality of this function, but perhaps we would also send in a second string that's a sentence to write to the file. We could do that with a void function, but we wouldn't know if the file was found and written to or not.

For reference, the other use of void is so we can accept ANYTHING as a function argument. This can be dangerous, but as we all know, dangerous things are fun and cool.

To Be Continued)

70902©