Cplusplus

From Redbrick Wiki
Revision as of 17:53, 6 December 2007 by Coconut (talk | contribs)
Jump to navigation Jump to search

Under construction, LOL.

C++ is an object-oriented programming language, developed as a superset of the language C, which means that the language is, essentially, C with more features, hence the name. However, it has since evolved into a separate language and compatiblity with C is no longer guaranteed.

It is a very popular all-purpose language which is commonly utilised for game programming, and in many respects is quite similar to Java, another object-oriented language.

g++

The page Programming On Redbrick explains how to compile programs written in C++. Here we will go into more depth as to how the compiler g++ works.

A compiler works by translating your programming language (in this case, C++) into assembly language, which is the basic language that a processor understands. While C++ is a universal language (source code written on one architecture will generally work on another unless special libraries are used), programs must be recompiled if they are to be used on different architectures - for example, if you are compiling on murphy, which uses the UltraSPARC architecture, you will have to recompile your program if you wish to use it on carbon or deathray, which use the Intel x86 architecture, because UltraSPARC and x86 assembly languages are completely different.

g++ is the free, open-source C++ compiler which is included with many distributions of Linux as part of the gcc package, the latter of which is a C compiler. Other popular C++ compilers include Borland C++ and Microsoft Visual C++, however these are proprietary. gcc (and g++) is the most widely ported and universally available compiler in the world.

Getting started

To begin programming in C++ on RedBrick, you first have to log in. Once you've done that, you can create a new folder for your C++ files by utilising the following command

mkdir C++

This will create a directory called "C++" in your home directory. Open up this directory by typing

cd C++

Now you're ready to create your first C++ program. For this tutorial, we are going to use the nano editor, as it is simpler than the alternative, vim. Make a new C++ source file, that we will call "first", with

nano first.cpp

C++ source code files will generally use the .cpp extension - you may have noticed that C programs use .c

nano should be open, awaiting input. The first thing you should do is import the necessary libraries to allow input/output in your program. This is the only library we will use at this point. Make the following line 1 of your program

#include <iostream>

iostream (or, archaically, iostream.h) is a C++ header file, which is a file containing C++ code designed to be imported by multiple programs.

Now we want to create our main() function. main() is the first part of code that will be executed upon running your program. main() will typically look something like this

int main()
{
   // insert some code here
  
   return(0);
}

There are a couple of things that have to be explained here.

  • The function begins with int - an int in C++ means integer, which is simply a type of variable - in this case a number. Having the function declaration as int main() means that the function main() will return an int at the end of its execution. main() will always return an int.
  • Chain brackets { } are used to denote the code which main() contains. When you call main(), the code between these brackets will be executed.
  • // is used to make a comment. A comment is a line in your source code which will be completely ignored by the compiler. This is handy for explaining what your code does and you should quickly learn to use them frivilously.
  • return(0); is placed at the end of your main() function. The 0 is the int which is returned by the function - in this case, 0 means the program executed without any problems. Yay!!! The ; is used to mark the end of a line where a command is issued. If you omit this semicolon, the compiler will whinge at you.

So, at this point your program should look like this

#include <iostream>

int main()
{
   // insert some code here
  
   return(0);
}

The Programming On Redbrick page explains how to compile C++ programs. Just to recap, we'll go over it again (oh joy!) To indent your code as shown above, press TAB. (Proper indentation is essential programming practice.) Press CTRL+O to bring up the save option, enter to save and then CTRL+X to exit.

g++ -o first first.cpp

The -o parameter allows you to tell the compiler where you want to have the compiled program saved and what you want its name to be. In this case, it'll be compiled to the same folder as your source file, first.cpp

Your program should compile. If it does, run it by entering

./first

Nothing will happen. That's because we haven't told the program to do anything!

Wow your ma with a basic program

Open up your source file again and delete the comment line. Now it's time to get stuck into some real code.

Change your program so it now reads

#include <iostream>

int main()
{
   std::cout << "This is my first real C++ program. Epic lulz!" << std::endl;
  
   return(0);
}

If you compile this, the program should execute and print this line onto the screen

This is my first real C++ program. Epic lulz!

Hurrah! Something useful and/or interesting!

  • cout is the C++ command for issuing an output. By default, this will go to the screen. Use left-facing arrow thingies (<<) to put your output into the cout command. You can link several things together by using multiple pairs of arrows as seen in the code, without having to issue cout twice.
  • endl moves output to the next line on the screen. It also flushes the stream... whatever that means.
  • std is the namespace which contains cout and endl. We could include the entire namespace in the code, but for now we don't need to since we're only using two of its functions - therefore we'll access them directly by putting std:: in front of cout and endl.
  • The text between the " " is called a string of characters. In C++, strings are always put between inverted commas like this.

To be updated later...

Variables and operators

So, you've created your first C++ program. You must be so proud of yourself. Here's where the pain begins. We're moving on to variables and operators.

A variable is a data container which you assign a value and whose value can, by default, be changed during the execution of your program. That's why it's called a variable.

In C++, there are four variable types which you will use most

  • int as explained earlier, is a number.
  • char is a single ASCII character - a letter, a number or a symbol.
  • double is a decimal (floating point) number, for example: 5.673 or 1.0
  • string is just a string (array) of characters - you need to #include the string library for this to work as a data type.

There are other ones which you won't need as often

  • short is, depending on the compiler, a number whose bit length is shorter (or sometimes) equal to an int.
  • long has a bit length twice that of an int.
  • float is a decimal (floating point) with half the precision of a double - shit, in other words. Avoid unless you're running on a system with memory measured in kilobytes and desperately need to conserve space, like the D6. God help you.

To initialise a variable such as an int, simply use the line

int a;

This reserves memory space for an int called a. But this isn't much good, is it? We need to give it a value. If you declare the variable like above, you can later assign a value like this

a = 5;

Now a has the value of 5, however, this is the n00bs' way of doing it. Why not declare and assign at the same time?

int a = 5;

That's more like it. You'll be a RB admin in no time. Let's run through initialising other variables.

int a = 5;
double b = 10.463;
char c = 'H';
string d = "Warning: Haskell may contain traces of anti-lulz.";

Hopefully you're getting the idea. Now that we're using string, we will have to start using the namespace std in our code for the sake of speed. Because of this, you will notice the absence of std:: which may make things easier for you.

We can throw the above code into a program and make it output the variables to the screen

#include <iostream>
#include <string> // Remember to include string if you're using a string!

using namespace std; // Also remember this!

int main()
{
   int a = 5;
   double b = 10.463;
   char c = 'H';
   string d = "Warning: Haskell may contain traces of anti-lulz.";
   
   cout << a << endl << b << endl << c << endl << d << endl;
   
   return(0);
}

Note how we can print four lines, with four different variables, using one cout command by having multiple <<

Also, see how string uses inverted commas " " whereas char uses two apostrophes ' ' - this is called being unnecessary complicated. But at least this isn't Haskell, so cheer up.

So, say you want to add two numbers together for some reason which makes sense to you. How? Simple. There are several ways to do it.

int a = 2;
int b = 6;
int c = a + b;

The value of c is now the values of a and b added together. If you don't want to bother with a third variable, you can just put the answer into a or b by replacing the third line with

a = a + b;

To output c to the screen

cout << c;

Or, without having to use c at all

cout << a + b;

This adds a and b together and outputs it to the screen all in one go. Hurrah!

You can also add doubles together in the same fashion.

Say you have a few chars and you want to combine them together in order to form a word, and then print it to the screen

char a = 'o';
char b = 'm';
char c = 'g';
char d = 'w';
char e = 'a';
char f = 'f';

cout << a + b + c + d + e + f;

This will print "omgwaf" on the screen.

Another way to do it, without using variables at all, is

cout << "omgwaf";

You can also waste everyone's RAMz if you want, by using a string for no justifiable reason. Say you've already declared the chars and assigned their values

string rofl = a + b + c + d + e + f;

cout << rofl;

Remember: a string is merely an array of characters so this works with strings too. You'll learn more about arrays later.

There are other basic operators in C++.

  • + is the addition operator. It allows numbers to be added and chars and strings to be joined together.
  • - is the subtraction operator. With it you can subtract numbers.
  • * is multiplication. Multiply numbers.
  • / is division. Divide numbers.

Say you want C++ to do your maths homework for you because you feel Michael Clancy is going to fail you for being such a newb.

int a = (5 * ((12/3) - 1)) + 25

Easy as undone's mother.

This will divide 12 by 3, giving 4, then take 1 from it, giving 3, multiply that by 5, giving 15, and then add it to 25, resulting in 40, which is then assigned as the value for a. Try it yourself. Brackets are very handy for mathematical calculations in C++, just like in that yoke known as "real life".

C++ can also handle negative numbers, just as you would expect a calculator to, except this time the calculator can run 32 threads simultaneously, is about one hundred times bigger, ten thousand times louder, needs several hundred watts of power to function and only the five richest kings of Europe can afford one.

Perhaps that last part was slightly untrue.

if statements and advanced operators

A crucial element of any programming language is the ability to test whether something meets a defined condition. The most basic way of doing this in C++ is by using the if statement. Here's an example of how if and else work

#include <iostream>

int main()
{
   int a = 4;
   
   if(a == 5)
   {
      cout << "a is 5." << endl;
   }
   else if(a == 4)
   {
      cout << "a is 4" << endl;
   }
   else
   {
      cout << "a does not equal 4 or 5." << endl;
   }

   return(0);
}

If is 5, the program will return "a is 5.", if it is 4, the program will return "a is 4". If it is neither 5 nor 4, the program will return "a does not equal 4 or 5."

You can use an infinite number of else if statements, linking ifs together, but it is probably bad programming practice to use too many.

Also note that if you only have one line of code following an if, if else or else statement (the line which will be executed when the condition is satisfied), you may omit the chain brackets for the statement.

if(a < 10)
   cout << "a is less than 10." << endl;

If a is less than 10, the program will return "a is less than 10."

  • == is used to see if two variables are equal. It will work for all data types except string, for which there are other functions dealt with later.
  • != not equal to
  • <= less than or equal to
  • >= greater than or equal to
  • < less than
  • > greater than