Spunky's C++ Tutorial

Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
Part I: The Basics

Chapter I: Getting Set Up

First things first. Before you'll be able to make use of this series of tutorials, you'll need to get a compiler. A compiler is basically a tool that allows you to translate a programming language (in this case, C++) to machine language, which is the language that your computer understands. Think of machine code (or binary, if you prefer that) as a series of switches, represented by 1s and 0s. A program (for example, Half-Life) is composed of a certain sequence of switches, which define how the program will do it's work.

There are a number of free compilers available. A good starting compiler that comes complete with an IDE (Integrated Development Environment) is Dev-C++. It's recommended, however, to buy a copy of Microsoft Visual Studio 2005 (or 2003, if you're learning C++ to code a Half-Life mod), as Dev-C++ is a slightly buggy development environment. You can download Dev-C++ from here.

I will not go into detail on just how everything in Dev-C++ works, as you only need the default settings for what we're going to be doing. After downloading and installing Dev-C++, and are able to start it up without problems, you should be ready to advance to the next lesson.
 
Beta Tester Squad
✔️ HL Verified
🚂 Steam Linked
💻 Oldtimer
Joined
Jan 26, 2005
Messages
3,089
Best answers
0
Location
Romania
WOW Spunky can't wait for it
 
Active Member
💻 Oldtimer
Joined
Nov 18, 2002
Messages
4,201
Best answers
0
hey, im interested!

But a main point for me is: will i be able to use those skills for the Hl2 engine?

thanks in advance
 
New Member
Joined
May 1, 2006
Messages
665
Best answers
0
@PiXel: Yeah it will.
@Spunky: Are you focussing on c++ or are you gonna give importance to HL Modding?
 
New Member
💻 Oldtimer
Joined
Aug 16, 2004
Messages
2,309
Best answers
0
Location
Sunnyvale, CA
I will love you forever if you make this tutorial. I want to learn C++ :)

PS. STICKY PLX
 
Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
@Spunky: Are you focussing on c++ or are you gonna give importance to HL Modding?
Just C++. I won't put any emphasis on modding, but you should be able to use the knowledge earned here for that purpose.
 

Mog

New Member
Joined
Feb 2, 2002
Messages
541
Best answers
0
This sounds pretty interesting... I already know a fair bit of c++, but I rarely use it... It's always good to read more tutorials though.
Good luck. :)
 
Busy Busy Busy
★ Black Lounger ★
💻 Oldtimer
Joined
Nov 24, 2001
Messages
1,439
Best answers
0
Stickified. I want to see where this goes :0)
 
Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
Chapter II: Your First Program

Just about every single tutorial out there starts with this. Here, we will write the simplest application there is: Hello World! As simple as this program is, you'll come to appreciate how much you'll learn from it. Shall we begin?

http://pastebin.ca/388844

Let's take this opportunity to test your compiler. Open up Dev-C++, create a new project by going to File -> New -> Project. Enter "HelloWorld" as the project name. Select "Console Application" as the project type. Then go ahead and click "Ok".

Remove the code that Dev-C++ automatically generates, and then copy and paste the code from above into your project. After you've done this, select Compile from the Execute menu. Dev-C++ will prompt you to save main.cpp to a location. Save it to the desktop for easy access. Wherever you save your project files is also where your .exe file will appear, so it's better if you don't have to search all over the place for it.

Now that you've compiled your source into an executable file, let's open it up and see what it does. Go to your desktop and open the .exe file that you just compiled. What does it do? Let's go over that now.

On line 1, we declare an include directive to the preprocessor. The preprocessor is a component of Dev-C++ (and most other compilers) that goes through before compiling the source, and looks for lines beginning with the # symbol. In this case, we tell the preprocessor to include another file into our source, iostream. iostream is a standard C++ file that handles input and output to the DOS prompt (or console). We need this to print "Hello world!" to the screen.

On line 3, we begin our program by declaring the main() function. main() is ALWAYS the function that gets called first, because it is, in fact, our main function. We declare main() to be of type int, or integer. This means that main() will return a whole number upon finishing it's tasks. We'll get more into this later.

On line 4, we open our block of code with a left brace ({). Every brace used to open a new block of code must be met with a closing brace to end the block of code. Everything between the braces are considered instructions to that specific function. We'll leave it at that for now. All you need to know is that every opening brace must be met with a closing brace.

On line 5:
C++:
std::cout << "Hello world!\n"; // Prints "hello world" to the screen.
We tell our program to print "Hello world!" to the screen using cout (pronounced "see out"), and then move on to the next line by using the \n tag. \n is short for newline, which does just what you would think: it creates a new line. There are numerous other tags as well:

Code:
\a - Alert
\b - Backspace
\f - Form feed
\n - New line
\r - Carraige return
\t - Tab
\v - Vertical tab
\' - Single quote
\" - Double quote
\? - Question mark
\\ - Backslash
\000 - Octal notation
\xhhh - Hexadecimal notation
A backslash (\), when used in a tag, is known as the escape character. The escape character changes the meaning of the character that follows it. For example, normally the letter n means the letter n, but when it is preceeded by the escape character, it means new line.

On line 7:
Code:
std::[COLOR=#0000dd]cin[/COLOR].[COLOR=#00eeff]ignore[/COLOR](std::[COLOR=#0000dd]cin[/COLOR].[COLOR=#00eeff]rdbuf[/COLOR]()->in_avail() + [COLOR=#0000dd]1[/COLOR]);
For right now, you don't need to understand what this line does. However, I will briefly explain what cin.ignore is and does. cin.ignore is a member of the std namespace that tells your program to ignore a keystroke (or multiple keystrokes) in the console window. In the parenthesis, we call a member of cin.rdbuf (in_avail()) as an argument (more on that later), and then we add 1 to it. This tells our program to ingore ONE pressing of the enter key when the program is finished.

On line 8:
Code:
[COLOR=#0000ff]return[/COLOR] [COLOR=#0000dd]0[/COLOR];
We tell our program that execution went smoothly, and it's okay to terminate. All functions must return a value (except for void functions, but we'll get to that later on). If they do not return a value, your compiler should flag an error until you do. This line tell our program to terminate, and return the value of 0 to the OS (operating system).

In conclusion, you learned a bit about namespaces and how they are used in a program. You also learned a bit about functions, and returning values from them. You learned how to use cout, a member of the std namespace, to print text to the console window. And you learned about the #include directive, which tells the preprocessor to include another file into our program.

If you have any questions, email me at [email protected] or post in this thread. I will do my best to address any confusion or concern.
 

Mog

New Member
Joined
Feb 2, 2002
Messages
541
Best answers
0
The tutorial is excellent so far, good start. :yes:

Your code didn't compile at all in my ancient old Borland Turbo C++ compiler.
For a start, it wanted the old &lt;iostream.h&gt; rather than the of the up-to-date &lt;iostream&gt; usage. :tired:
But I downloaded the newest Dev C++ like you said and it compiled fine.
I had a horrible old version of Dev C++ before which put me off, but the new version is amazing! Much better functionality and the layout is perfect.

Wouldn't std::cin.get() have been a lot more n00b friendly?
Your version of helloworld seems kind of overcomplicated... but because of that I learned a little from it. :)
 
ESF Old Timer
✔️ HL Verified
🚂 Steam Linked
🌟 Senior Member
Joined
Mar 4, 2007
Messages
646
Best answers
0
Location
Netherlands / Fryslan Boppe @ Drachten
I also learning C++ and so far spunky does it great.
And yes this is a good start to begin with.
Next to my book I also will follow lesson here :D.

Good job spunky :)
 
New Member
Joined
May 1, 2006
Messages
665
Best answers
0
Wouldn't std::cin.get() have been a lot more n00b friendly?
I agree lol.
Code:
std::cin.ignore(std::cin.rdbuf()->in_avail() + 1);
is complicated for a new programmer.
But interesting imo.
Hmm for some reason, my mingw compiler doesnt need this. It adds something on its own to every program to let the screen wait for 1 keystroke.

I used the old C version of using getch() for a long time (as long as I used turbo c++)
Anyways, good tut.:laff:
 
Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
Chapter III: Variables, Constants, and Enumerated Constants

In this chapter, we'll touch down on how to store and manipulate data in your programs. First, however, I feel it's important to explain a bit about memory.

When coders talk about memory, they are most often referring to RAM (random access memory). A long time ago, when memory was expensive, programmers had to write fast and memory-efficient programs. They had to be small, so as not to consume memory. However, most computers have at least 512 MB of RAM, if not more. The standard now is 1 GB, but that doesn't mean you can just go crazy with your memory.

The basic building block of a program is a bit of memory. No, seriously, think of a bit as a single locker in a locker room. You can open this locker, place things inside of it, and then close it again. If you need to access something inside of that locker later, you can open it back up again to use whatever it contains.

Variables are how we store data in memory. Each variable type consumes a different amount of memory, as each variable type is typically used for different things. Some can be used to the same effect as others, but it's important to know which to use in a section of your program. Below is a bit table. It will come in handy to know this information later, when you're programming larger and more complex programs:

Code:
1 bit = 1 bit
 
8 bits = 1 byte
 
1024 bits = 128 bytes = 1 kilobit
 
8192 bits = 1024 bytes = 8 kilobits = 1 kilobyte
 
1048576 bits = 131072 bytes = 1024 kilobits = 128 kilobytes = 1 megabit
 
8388608 bits = 1048576 bytes = 8192 kilobits = 1024 kilobytes = 8 megabits = 1 megabyte
 
1073741824 bits = 134217728 bytes = 1048576 kilobits = 131072 kilobytes = 1024 megabits = 128 megabytes = 1 gigabit
 
8589934592 bits = 1073741824 bytes = 8388608 kilobits = 1048576 kilobytes = 8192 megabits = 1024 megabytes = 8 gigabits = 1 gigabyte
You don't need to memorize this, although it never hurts to know about memory usage in your programs. Each bit is a locker in which a piece of information is stored. The locker itself is just a black box as far as we're concerned. That's the beauty of modern programming. You don't need to know half of what your program is doing. You can just sit back and trust that it's doing what you want. The only thing you need to concern yourself with is what YOU tell it to do.

Now let's move on to the different variable types. Below you will find a table displaying the different variable types and their uses:

Code:
int - A variable of type int (or integer). Typically used when working with whole numbers. Variables of type int consume 2 bytes of memory on most machines, but sometimes can consume 4 bytes of memory.
 
unsigned int - The same as type int, but only uses positive integer values. No negative values can be used when working with a variable of type unsigned int. Also consumes 2 bytes of memory (again, depends on the system).
 
long int - Same as an int, but consumes 4 bytes of memory instead of 2 bytes, allowing much larger values to be stored.
 
short int - A variable of type int defaults to short int on most compilers. Check your compiler's manual for more information.
 
bool - Variables of type bool hold boolean values. That is, true or false values.
 
float - Variables of type float hold floating point number, or real numbers. That is, numbers with decimal places. This gives added precision to calculations, but consume more memory and can take longer to process on slower machines.
 
double - Variables of type double also hold floating point numbers, but use twice the memory as a float variable. This allows for larger values, but is far more inaccurate due to the size of the values you will typically be manipulating with this variable type. In most cases, it's better to just stick to float for floating point numbers.
The size of the various types can be different for different systems, so to check how much memory each type uses on your system, we're gonna run through a nifty little program that will tell us just that. Using the sizeof function, we can find the size of pretty much any type out there. Let's check it out: http://www.pastebin.ca/944567

A constant is a variable that never changes. This is useful when you need a variable that you can't risk being unknowingly changed by another part of your program. This also allows for easy access of said variable throughout your program. For example, you could declare a constant for PI, as follows:

Code:
const float PI = 3.14159265
Now you have a never-changing variable to hold PI.

Now let's check out a sample program to illustrate constants at work: http://pastebin.ca/934918

Your compiler should flag an error (or errors), basically saying "hey, you can't change a constant you idiot!"...

Am getting around to finishing this chapter... As always, if you have any questions, ASK!
 
New Member
Joined
May 1, 2006
Messages
665
Best answers
0
Spunky said:
You don't need to know half of what your program is doing. You can just sit back and trust that it's doing what you want. The only thing you need to concern yourself with is what YOU tell it to do.
*Nods* But it would still be better if you did know what its doing. But later on this becomes a pain in the ...
Especially with stuff like recursion. I never get my analysis of recursion right. Darn. That could explain my problems debugging that darn problem of the towers of hanoi. But even if you don't get it at the advanced level, make sure, you do at the initial stages. Then itll become easy figuring out which line is making the error and why.
And oh, about memory and cleanups after you allocate them. Remember that most books were written during the dark ages of Turbo C++. The present day compilers are always seeking ways to remove unused variables. But that applies for huge programs where memory allocating and deallocating takes like a lot of time. But with small problems that dont go beyond 100 lines, learn to clean them up yourself.
 
Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
I never get my analysis of recursion right.
Solving a mathematical equation by having the equation reference itself. Good enough for ya? :p

Edit: Actually, I got curious and looked it up. I wasn't far off, but here it is:

Wikipedia said:
Recursion is the process a procedure goes through when one of the steps of the procedure involves rerunning the entire same procedure.
 
New Member
Joined
May 1, 2006
Messages
665
Best answers
0
lol, I should have been clearer. I meant whenever I try to analyse some program with recursion to find out how many times the function calls itself, i go wrong.
I know you can just use a counter, but I feel sometimes, it pays to use the mind rather than the compiler alone.
 
Freelance Mappzor
✔️ HL Verified
🚂 Steam Linked
💻 Oldtimer
Joined
Nov 21, 2003
Messages
17,065
Best answers
0
Location
Stairing at the Abyss
lol, I should have been clearer. I meant whenever I try to analyse some program with recursion to find out how many times the function calls itself, i go wrong.
I know you can just use a counter, but I feel sometimes, it pays to use the mind rather than the compiler alone.
You have to use some sort of counter. If you dont you have an endless loop.

The program never stops to call itself untill it crtashes due to having no more space to save the variables.

Basically the counter is the part of the code that tells the program to stop making the recursion.

Anyhow you cant have recursion without this baby. The tower of hanoi program (clasic).
Code:
#include <stdio.h>

void hanoi(int n, char a, char b, char c){
	if (n>0)
	{
		hanoi(n-1,a,c,b);
		printf("Ring %d: from %c to %c\n",n,a,c);
		hanoi(n-1,b,a,c);
	}
}

main()
{
	int x;
	printf("How many rings will your hanoi tower have?");
	scanf("%d",&x);
	printf("\n");
	hanoi(x,'a','b','c');
}
 
Active Member
✔️ HL Verified
💻 Oldtimer
Joined
Nov 6, 2004
Messages
3,055
Best answers
0
Location
Round Rock, TX
@ Grega - Yes, the tower of hanoi puzzle is a great recursion excercise. However, let's try to keep it to C++, shall we? I don't want people getting confused.
 

Users who are viewing this thread

Top Bottom