Jump to content

Cplusplus: Difference between revisions

5,937 bytes added ,  22 October 2008
m
opcode only specifies an instruction. Machine code (of which assembly language is a human-readable representation) is accurate.
mNo edit summary
m (opcode only specifies an instruction. Machine code (of which assembly language is a human-readable representation) is accurate.)
 
(20 intermediate revisions by 2 users not shown)
Line 1: Line 1:
''Under construction, LOL.''
'''Under construction.'''


'''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.
''If you have any problems with this tutorial or want to give feedback, ask questions or get additional help, please e-mail coconut<at>redbrick<dot>dcu<dot>ie or, for general [[Helpdesk]] queries, helpdesk<at>redbrick<dot>dcu<dot>ie. ''
 
'''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 compatibility 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.
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.
Line 7: Line 9:
==g++==
==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.
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.
A compiler works by translating your programming language (in this case, C++) into machine code, 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.
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.
Line 19: Line 21:
  mkdir C++
  mkdir C++


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


  cd C++
  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
Now you're ready to create your first C++ program. For this tutorial, we are going to use the [[nano]] editor. Make a new C++ source file, that we will call "first", with


  nano first.cpp
  nano first.cpp
Line 68: Line 70:


  g++ -o first first.cpp
  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
Your program ''should'' compile. If it does, run it by entering
Line 232: Line 236:
Perhaps that last part was slightly untrue.
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>
using namespace std;
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
==Loops==
Most programming languages support '''loops''', which are useful for executing a certain part of code over and over.
Here is a '''while''' loop
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    while(a < 100)
    {
        cout << a << endl;
        a++;
    }
    return(0);
}
This will print 100 lines of numbers, going from 0 to 99
0
1
2
3
4
5
...
The condition to make sure that a is less than 100 is checked at the start of each loop, and a is incremented by 1 at the end of each loop (denoted by '''a++'''; you can also use '''a--''' to decrement by 1). Therefore, when a reaches 99, it will be printed to screen, then incremented. The loop will then check to see if it is less than 100, which it is not, resulting in the termination of the loop.
While loops are handy in games where you may want something to loop endlessly until the user makes an action (presses a key, for example). Here is a variation of the while loop, called the '''do while''' loop.
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    do
    {
        cout << a << endl;
        a++;
    }
    while(a < 100);
    return(0);
}
This print the same 100 lines, 0 to 99. However, the condition for the loop is not checked until the end of the loop.
If you're dealing with finite numbers of loops, you may want to consider the '''for loop'''
#include <iostream>
 
using namespace std;
int main()
{
    for(int a = 0; a < 100; a++)
    {
      cout << a << endl;
    }
    return(0);
}
This produces the same result, except in a much handier format. There are three things you declare when creating a for loop: a variable, what condition must be met for the loop to continue cycling, and what happens at the end of a loop. a is the initialised variable, the loop will continue until it reaches 100 and at the end of each loop, a is incremented by 1. Simple.
To end a loop immediately, issue the following command in your code
break;
For example, if you want the loop to end early when a certain condition is met, just use an if statement inside the loop and have the loop break if this condition is met.
==Executing system commands in C++==
It is possible to execute system commands from within your C++ program. If your program is command-line only, you can execute simple commands such as those to clear the screen, etc.
If you're using Linux, the code is
system("clear");
You can also do this if you're running Windows (although why would you want to?) The DOS clear command is "cls"
system("cls");
...like so!
However, it is recommended that you '''not''' use system commands in your code for something as trivial as clearing the screen. It's a resource hog and leaves a gaping security hole in your C++ program. There is a better way to do this in C++, however it requires advanced knowledge of the language and is available below under ''Advanced''.
==Functions: The Basics==
It's now time to move on to '''functions'''. A function is basically the same thing as a method in Java: it is a sequence of commands which can be called upon at any time, passed parameters and set to return a value.
main() is a function - the default function for a C++ program. But what if you have some code that you don't want to put into main? Use another function.
Let's say we want to add two numbers together and print out the result. The code could look something like this:
#include <iostream>
using namespace std;
int add(int a, int b)
{
    return a + b;
}
int main()
{
    int a = 2;
    int b = 5;
    cout << add(a,b) << endl;
    return(0);
}
This program adds 2 and 5 together to get 7, and displays this answer on-screen.
a and b are passed as ''parameters'' to the add function - they are then immediately added together and the answer is returned. Experiment with this code to do different things.
==More advanced C++==
I'll get around to this someday. I'm still learning too you know!
[[Category:Helpdesk]]
[[Category:Helpdesk]]
244

edits