Saturday, December 20, 2008

C++ basics

C++ tutorial: Part 1

1: The IDE

With this article, I am hopefully beginning a series of C++ tutorials for complete beginners.
Before you start you will need an IDE (Integrated Development Environment), or alternatively just a text editor and a compiler. An IDE is just a text editor with built-in compiler and debugger.

What is a compiler? A compiler is a program that translates your C++ code into binary instructions that the processor can work with. Ideally we would just tell the computer what to do, and it would obey. But this isn't so easy, since humans are not computers, and computers are not humans. Therefore there is a language barrier, and programming languages try to bridge the gap with a compiler (translator). To be really specific about it, your program doesn't end up as pure cpu instruction, but is laid out in a file format that your operator can help the processor execute.
This is the reason a windows program doesn't work natively on linux, and vice versa.

For IDE I would recommend Dev-Cpp from www.bloodshed.net or Code::Blocks. There are also full-fledged professional development environments for professionals, such as Microsoft Visual Studio (MSVS for short) which costs money, and its little sister, Microsoft Visual C++ Express.
There are free Express editions available for every language supported by Visual Studio, so if you want to get used to an environment that excels at building applications for Microsoft Windows this is probably where you want to go.

Personally, I don't like using msvs for several reasons:

* It's not portable (you can only build programs for windows with it)
* It's bloated (takes a while to load)
* The menu system is too advanced for my feeble mind

In short, I like my IDE light-weight and portable. This is why I don't really use an IDE at all.

So, what do I use? Well, since I want it light-weight, I use a small text editor and a command-line compiler. Don't fear; after developing a few command-line programs you will lose the fear of operating such utilities. Since my main Operating System (OS) is Windows, I use MinGW, which is a Windows port of GNU's compiler collection. The way I've installed this myself is by installing Dev-Cpp and pointing my systems "PATH" environment variable to the bin directory of the compiler (see picture that I will add later, please remind me!).
This allows me to open a command prompt, navigate to my code, and write

c++ -o name codefile.cpp

Yes, this is as easy as it looks. c++ is the name of the program, the -o switch allows you to specify a name for the compiled file, and that's that. If you don't specify a name with -o, the compiled file ends up as a.exe.

Set up your favorite IDE, and let's get coding!


2: Hello World!

Our first program:


#include <iostream>
using std::cout;

int main()
{
// This is a comment and is ignored by the compiler
cout << "Hello, world!\n";
return 0;
}

This prints "Hello, world!" to the screen, with a newline on the end.
"\n" is a newline character, changing line like enter would in notepad.

VERY IMPORTANT: Every "statement" (command) ends with a semicolon (;).

Let's go through it from the top:

#include <iostream>

When the compiler encounters an #include line, it searches its folders for a file of the name between the brackets (greater-than and less-than signs), and if found the line is replaced by the contents of the file. In this case, iostream defines stuff we use later in the code, such as cout.

using std::cout;

This has to do with namespaces which is an advanced topic, but basically it tells the compiler that we don't want to write std:: in front of cout for every time we use it. Std stands for standard, meaning this is a functionality of the C++ standard library (stl). You can also write

using namespace std;

if you use a lot of stuff from the stl.

So, you've already learned an operator! More about that later, but you probably know a few more from before.

int main()

This is a function declaration. A function is a shortcut to a functionality of your program. The main function in any C++ program is the "entry point", that is, when the program is run, it starts from the first line inside main.

Inside? That is what we use the { and the } for. These curly braces are known as a "scope". The function ends when its scope ends.

Moving on to the line prefixed with //, this is a comment and will not be looked at when the compiler tries to translate your code to instructions.

Next up, cout:
This is where all the magic happens. Remember that file we included? It defines a function called cout which is short for console output. So whatever you "shift left" into it is written to the screen. return 0;

To tell you what this line does I think it's about time to tell you about data types and variables.

3: Variables

So, we are making a little program, and we are using cout's evil twin called cin (you guessed it, console input) to get a value from the user. Here is the program:

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

int main()
{
string name;
cout << "Please enter your name: ";
cin >> name;
cout << "Hello, " << name << "\n";
return 0;
}


This program asks for your name and greets you with it. To be able to do this, we have to store your name temporarily. So we put it into a little box called a variable, and write "name" on the lid of the box. So when we want to use the name again we just refer to this box instead.

Let's talk about data. Data can be of several types. To the computer all data is just binary numbers, but this would make it hard to work with for humans. So when programming, we categorize our data into different datatypes:


















int (integer)these are whole numbers (and take up 4 bytes)
char (character)These are characters, including letters, numbers and symbols. (takes up 1 byte)
bool (boolean)Can be either true or false (takes up 1 byte)
float (floating point number)A number with a decimal comma somewhere in it
long (long int)Can store a greater range of values than a regular int
doubleTwice the precision of a float
short (short int)Ideal for small numbers if you're concerned about memory use (2 bytes)
voidThis is used in special cases when no data is used

On the numeric types you can specify it being signed or unsigned, signed meaning it can be negative.

In addition there are other types such as string, that are not standard C++ (see we included <string> up there?)

So in our function declaration

int main()

we specify that main is a function of type integer. This means that it returns an int.
So after the program runs, it returns a 0 to the operating system (which "called" it to start the program). Operating systems use integer return values to determine if a program executed properly. This comes in handy to check for errors later.

So, let's get to those pesky operators next...

4: Operators

You probably know a few of the operators from before. Here they are:

































+plus
-minus
*multiplication
/division
%modulo
<<shift left
>>shift right
&&logic AND
||logic OR
!logic NOT
==equality
!=inequality
= assignment
++increment (+1)
--decrement (-1)

The modulo operator is quite useful if you have a random number and want it to be within a certain range.
For example, we have 300 and want it to be a number from 0 to 24. If you were to count to 300, but resetting to 0 every time you reached 24, you would end up at 300 % 24 which is 12.

The logic operators come in handy when you use conditionals.

5: Conditionals

if (this is true) { then do this } else { if not, do this }

This should be pretty self explanatory. To illustrate how a boolean works,

bool b = true;
if (b)
{
cout << "b is true";
} else
{
cout << "b is false";
}

While is also pretty self explanatory if you know english.

while (b) { if (1 != 1) { break; } }

This is a "while loop". While the condition is true, it executes what's in the braces. Break exits the loop. Try to guess what this one does.

Another type of loop is called "for":

for (int i = 10; ++i);

Here you declare a variable, then set the condition, then set what to do for each time the loop is finished running through.

All except for the condition are optional and you can leave them blank if you so desire.

Now let's declare our own function:

int multiply(int x, int y)
{
return x * y;
}

What this does should be fairly understandable if you made it this far. It multiplies its two inputs and returns the value. In other words, it returns the product of its inputs.


That's it for now. My tutorial basically sucks compared to learncpp.com, so you should check that out

until next time. :)

- h3x

No comments:

Post a Comment