1.1. The main() function

Your console program starts and ends in the main function. The main function can be defined in a variety of ways, depending on both your personal preferences, the C++ standard and whether or not you intend to parse command line options. A fairly standard main function can be defined as follows:

int main()
{
...
return 0;
}

It is very important to note here that main must return an int according to the C++ Standard. Whether or not your compiler wrongly accepts void main() as valid, if you use that then your program is non-conforming. A further point to note is that return 0 is technically not required according to the Standard, although it is generally considered good programming practice to include it.

Note that some of the words are coloured blue: these are C++ keywords. The simple definition of the main function naturally leads on to several more complicated topics which are vital to understanding C++. You may find these next sections a little difficult at first; if so keep re-reading them until you feel comfortable with the concepts presented.

1.2. Variables

There are many intrinsic (built-in) variable types in C++, many of which you don’t need to know yet (if ever). This table summarises some of the common ones you are likely to encounter. Note that anything written in [] is optional.


char (Character)
bool (Boolean : true / false)
double (Double-Precision)
float (Single-Precison)
int (Integer)
unsigned [int] (Unsigned Integer)
long [int] (Long Integer)
unsigned long [int] (Unsigned Long)

As you can see these will need some explaining. Firstly, a floating-point number is any number which is not an integer. For example 3.14 is a floating-point number. Clearly computers cannot store such numbers to infinite decimal places, hence we have both single-precision floating-point numbers and double-precision floating-point numbers which can store numbers to varying degrees of accuracy. Using doubles is preferable on the whole, since they store more significant figures and are just as fast as floats. The only time when using floats is preferable is when memory is at a premium. The second important concept is that of signed and unsigned numbers. At this point I could go into a section about how numbers are stored in binary form but it would bore you silly, so suffice to say that signed numbers are interpreted as either positive or negative whereas unsigned numbers are interpreted as positive. This means that if we use unsigned numbers for variables which can only be positive we can store numbers roughly twice as big as if half of our “allowance” was wasted on negative numbers. To make things simple, just use signed variables for now.

Now that’s out of the way (phew!) we can get on to how to actually declare variables. Well, actually we can’t, because I need to explain the difference between declare and define first or you will get it wrong forever (I did). Basically declaring something is telling the compiler it exists, defining it is declaring it and actually initializing it with a value as well. This means that all definitions are actually declarations as well. It’s quite difficult to show the difference with variables, so I’ll return to the theme when I cover functions. For now, to define (and simultaneously declare) a variable we do something like this:

int a;

Note the semi-colon at the end of the line. It has to be there because it’s the end of a statement.

1.3. Commenting

Returning to our original program, we could now add some variables in and maybe even try changing their values with mathematical operators. Firstly, I want to introduce commenting. There are two ways to comment in C++:
1) The old C way
/* This is a comment */

/*
So is this
*/

2) The new C++ way
// This is a one-line only commenting method
// The following statement is illegal
//
This is not a way of commenting (this statement will be read and the compiler will attempt to compile it : an error will occur)

Comments appear in green by default.

1.4. Mathematical Operators

Here’s a program which fiddles around with a few numbers. It is heavily commented (for heavily read unnecessarily) and uses some mathematical operators which we will cover straight away afterwards:

int main()
{
int a=5; // a contains 5
int b=10; // b contains 10
int c=a*b; // c contains 50
int d=a/b; // d contains 0 (rounded down)
double e=(double)a/(double)b; // e contains 0.5
return 0;
}

The mathematical operators which you will make most use of are +, -, * and / (where * is multiply and / is divide). You should understand most of the last program with the possible exception of the line int d=a/b; where d contains 0 despite the fact that 5 divided by 10 is ½. Simply put, integers can only contain whole numbers. If you forget this you will be in big trouble because you will get lots of weird logic errors which shouldn’t be there at all. Even if we had made d a double it would still have contained 0. The reason is that the compiler evaluates the expression and then stores it in d. It takes simply the integer part of 0.5 (i.e. 0) and puts it in d. Oh dear, we are screwed, you think. But in fact, what we actually have to do is simply convert one or more of the numerator and denominator to doubles before dividing; the result of the expression is then a double which contains the correct answer, this is then stored in e.

1.5. Displaying Text

Disclaimer: The usage of the word string in the following passage might be misleading. In this context I am referring to null-terminated C-style “strings,” rather than instances of the std::string class.

Manipulating numbers is great, don’t get me wrong, but what the heck’s the point if you can’t see them? Text in C++ can be stored in null-terminated arrays of characters (ok, nowadays most people use the Standard Library’s string class but that’s not the point here). What is an array, you ask? Examine this line of code:

int a[5];

What do you think it does? If you guessed that it creates 5 integers which can be accessed using the name a, you are perfectly right. Arrays contain a certain number of elements (however many you choose ignoring memory limitations) which are numbered from 0 onwards. For example, in the five-element array we see above, there are elements from 0 to 4. If we wanted the 3rd element, therefore, we would write a[2]. Returning to our text-based theme, if we wanted to store some text (called a string), we would use a character array which was as long as the string we wanted to put in it plus one additional byte, since as I said above strings are null-terminated which means they end in 0 (also seen as ‘\0’, the escape sequence for the null-terminator), telling the compiler that the string is finished. So, we could write the following:

char test[5] = “Test”;

The compiler will add the terminating null-character for us. Now if we want to display this text on the screen, we could write:

printf("%s", test);

You can accept this at face value, but if you’re a questioning sort of person like me you’ll be wondering what the hell’s going on here. Basically printf is a function which is defined as follows:

int printf(const char *format [, argument]…);

If you don’t know what a function is, don’t worry, read the next section first and come back here! Just to explain, format is a string which specifies exactly what else is going to be given to the function (known as passing to the function as a parameter / argument) since printf can take any number of optional arguments as we can tell from the fact that it has an ellipsis (…) as part of its function declaration. Don’t worry how it does it (all will be explained later), just accept that you need to specify the type of the arguments you’re passing to it so that it can display them correctly. In our case, %s is the format code for a string, which is what it’s getting.

Returning to our original example which used numbers, if we wanted to print out all our values from the program we wrote and then move onto a new line, we could simply write:

printf("%i %i %i %i %f\n", a, b, c, d, e);

As you can see, the function is nice and flexible, but also rather complex. Later on in the course we will cover stream input/output (the C++ method) which makes your life so much easier. Note that the \n is what is called the escape sequence for a line feed (ASCII character 10).

1.6. Functions

Functions are distinct subsections of a program which perform specific tasks. They can be passed variables as parameters and use them, and they can return a value. Alternatively, they can choose not to return any value, in which case they are declared as follows:

void MyFunc([parameters]);

The void keyword is useful for several things, but they are not something I’m going to deal with now. If functions return a value, they are declared thus:

type-specifier MyFunc([parameters]);

It’s easier to demonstrate than to explain, so without more ado here is a function which returns the number passed in + 5:

int AddFive(int num)
{
return (num+5);
}

The function takes one parameter (num) of integer type and returns an integer. The return statement returns whatever follows it from the function, in this case the original number we passed in + 5. Now, say for example we wanted to write a function which added two numbers together and returned the result. How would we go about doing that? First, consider what information the function needs to be given and what information we want back from it. It needs two numbers, which we will call a and b, and it returns the sum of the two. For our example, we will impose the restriction that a and b are integers, and that therefore the function will return an integer. We will also assume for now that the result will always be within the range which can be stored by an integer (INT_MIN <= result <= INT_MAX). This function does the job:

int Add(int a, int b)
{
return (a+b);
}

1.A Practice Tasks

You could read for a day about programming and learn nothing. To get to grips with C++, you’re going to have to write some actual code. Try these; if you get stuck look back at the above sections:

i) Write a function which multiplies two numbers together and returns the result. You are given that the two numbers are integers and therefore that is all the result needs to be.

ii) Write a function which takes two integer parameters, divides the first by the second, and returns the result. You should take account of the possibility that the result of the division will not be a whole number and adjust your code accordingly. Whilst you do not as yet know how to handle such a case, you should also realise that since dividing by zero is an error; there is a possibility that someone using your function could theoretically cause the entire program to crash. We will cover how to deal with this eventuality in later sections.

iii) Write a function which takes an integer parameter and prints it to the screen.

Tags: , ,

One Response to “Elementary C++: part 1 of 3”

  1. compiler says:

    Whether or not your compiler wrongly accepts void main() as valid, if you use that then your program is non-conforming. A further point to note is that return 0 is technically not required according to the Standard, although it is …

Leave a Reply

You must be logged in to post a comment.