Nothing Special   »   [go: up one dir, main page]

Netacad

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

A computer, even the most technically sophisticated one, is devoid of even a trace of intelligence.

You could say that it is like a


well-trained dog – it responds only to a predetermined set of known commands. And sometimes, like a dog, it just shuts down
and refuses to do what it’s told. The recognized commands are very simple. We can imagine that the computer responds to
orders like “take that number, add to another and save the result”.

A complete set of well-known commands is called an instruction list, sometimes abbreviated to IL. Different types of
computers may vary depending on the size of their ILs and the instructions themselves can be entirely different in different
models.

The IL is in fact an alphabet that is commonly known as machine language. This is the simplest and the most primary language
we can use to give commands to our computer. We can say it's the computer’s mother tongue.

It is possible (and this is often done in practice) for a computer program to be coded directly in machine language using
elementary instructions (orders). This kind of programming is tedious, time-consuming and highly susceptible to a
programmer's mistakes. During the early stages of computer technology, it was the only available method of programming,
and it very quickly revealed its serious flaws.

Programming in machine language requires full knowledge of a computer’s hardware design and its internal structure. This also
means that replacing the computer with one that differs in design from its predecessor can make the programmer’s entire
knowledge unusable. Also, the old programs could be completely useless if the new computer used a different IL. Thus, a
program written for a specific type of computer could be completely useless to other computers and vice versa. Secondly,
programs written in machine language are very difficult to understand for humans, including experienced programmers. It is
also the case that to develop a program in machine language takes a lot of time and is very costly and cumbersome.

All these circumstances lead to a need for some kind of bridge between the people's language (natural language) and computer
language (machine language). That bridge is also a language – an intermediate common language for both humans and
computers working together. Such a language is often called a high-level programming language.

A language like this is at least somewhat similar to a natural language: it uses symbols, words and conventions readable to
humans. This language enables humans to express complex commands for computers.

You may be asking how to persuade a computer to understand programs written in this way. Try as you might, encouraging the
computer is just not enough, but you can translate your program into machine language. Moreover, the translation can be done
by a computer, making the whole process fast and efficient.
How great is that? You don’t need to learn a whole bunch of different machine languages – you just need to know one high-
level programming language. If there is a translator designed for a specific computer, you can run your program without any
problems. In other words, the programs written in high-level languages can be translated into any number of different machine
languages, and thus enable them to be used on many different computers. This is called portability.

The translation we are referring to is made by a specialized computer program called a compiler. The process of translating
from a high-level language into a machine language is called compilation.

Now let's get back to more interesting issues related to the process of creating a new program. We already know that the main
task is to write a program in accordance with the rules of the chosen programming language. Such a program (which in fact is
just text) is called the source code, or simply source, while the file which contains the source is called the source file.

To write the source code, you will need a text editor that allows you to manipulate text without any formatting information (for
this reason Microsoft Word isn't a good choice - Notepad is better). This code is placed in a file and the name of the file should
imply its content. For example, it's common for a file containing the source code in the C++ language to have its name ending
with the suffix .cpp, so if you write a computer program and decide to name it proggie, it would be a good idea to put the source
code into a file named proggie.cpp. Some platforms may prefer other suffixes like cc, cp, cxx, c++ or even C (note that this is a
capital letter). Please consult your compiler documentation for details.

Next, your source code needs to be compiled. To do this you need to run an appropriate compiler and instruct it where you
stored the source code you want it to translate into machine language. The compiler reads your code, makes some complex
analysis, and then determines whether or not you made any errors during the coding process. If you have, it will tell you. This is
not to make you feel bad - these analyses are very insightful and helpful. But remember that they are made by a machine, not a
human, and you shouldn't expect too much from them. Okay, if your mistake was that you tried to add up two numbers
using  #  instead of  + , the compiler will kindly inform you of your mistake. However, if you typed  -  instead of  + , the compiler
can't guess that your intention was to add two numbers, rather than to subtract them. The compiler will not think for you. But
that's okay too. If the compiler did everything, developers wouldn't have jobs.

If the compiler doesn't find any mistakes in your source, the result will be a file containing your program translated into
machine language. That file is commonly called an executable file. The name of the file depends on the compiler you use and
the operating system you are working with. For example, most compilers designed for Unix/Linux system create an output file
named " a.out " by default. Compilers designed for use in MS Windows® can name the same name to this file as the source
file, while only changing the suffix from  .cpp  to  .exe .

Of course the whole process is actually a bit more complicated. Your source code might be huge and divided among several or
even dozens of source files. It may also be that the program was not written by you alone, but by a whole team, in which case
the division of sources into multiple files is simply a must. In this case, the compiling process splits into two phases: a
compilation of your source in order to translate it into machine language and a joining (or gluing) of your executable code with
the executable code derived from the other developers into a single and unified product. The phase of "gluing" the different
executable codes is commonly known as linking, while the program that conducts the process is called a linker.

What is the most common use of C++? It is the so-called object programming language, i.e. suitable mostly for large, complex
applications, especially those working in graphic environments. Knowing the C++ language is very helpful if you want to learn
C# or Java. The conceptual apparatus used by the C++ language is common for all object programming languages, as C++ is
one of the oldest languages of that class.

Further readings
If you take the learning of the C++ language seriously (and we expect nothing less of you), you will certainly not end your
education with this awesome course.

Among the hundreds of books written on the C++ language, there is one that we recommend in particular. The book has been
issued dozens of times all around the world and is available in over 20 different (natural) languages. The book’s title is simply
"The C++ Programming Language". It was the first book to describe the C++ programming language, written by the
language’s creator, Bjarne Stroustrup. Stroustrup began developing C++ in 1979 and currently – not surprisingly – is considered
the most important authority in this field. You can buy the book here.

Another book worth reading is "A Tour of C++" of the same author. It's rather a reference than a textbook. Don't use it to learn
C++ - use it to enhance you memory when you start to use C++ seriously. You can find it here.

One of the books that we particularly enjoy is one written by Alex Allain, called "Jumping into C++." It’s a great book for
beginners, presenting a step-by-step guide to becoming a C++ programmer. You can order the book here.

Last but not least, for those who aim to improve their programs and learn more about best practices in C++, there is a great book
by Scott Meyers, "Effective C++." You can order the book here.

For a more comprehensive list of good C++ books, you may wish to check this thread at stackoverflow.com.

If you know any other good books worth recommending, please feel free to contribute to this thread on our Facebook page.

Once you're a proficient programmer, you may want to have a source of knowledge through which you can quickly find the
answers to emerging questions, or just fill in the gaps in your memory. Instead of a handbook, you’ll want a book that briefly
describes the language standards - everything that’s really important and nothing more. You need what is called a report
(permanently improved and updated), published by the ISO standardization committee. You can find the most recent version
of the standard at https://isocpp.org/std.

But hey, it’s too soon for that. Look into that when you finish this course. No sooner.

Your first program


Now we’re going to show you a very simple (and, at the same time, completely useless) program written in the
C++ language. We’re going to use this example to present you some basic rules governing the language. The
program itself will be modified many times, as it becomes enriched by various additional elements in
expanding our programming knowledge. Ready? All right then, let’s go.

First we need to define our expectations for the program. They’ll be very modest. We want a short text to
appear on the screen. Let's assume that the text will state:

It's me, your first program.

output
That’s all we want at the moment.

What further steps should our first program perform? Let's try to enumerate them here:

1. to start;
2. to write the text on the screen;
3. to stop

This type of structured and semi-formal description of each step of the program is called an algorithm.
Sources of the word algorithm can be traced back to the Arabic language and originated in early medieval
times, and for us, this represents the beginning of computer programming.

Now it's time to see our program. It’s on the right side of the screen, in the editor.

It looks a bit mysterious, doesn't it? Let’s check out each line of the program carefully, and uncover its meaning
and purpose. The description is not particularly accurate and those of you who know a little C++ already will
probably conclude that it’s too simplistic and somewhat childish. We did this on purpose – we’re not building
Rome in a day. Not even in a week!

Let's move on.

Pay attention to the character # (hash) at the beginning of the first line. It means that the content of this line is the so-
called preprocessor directive. We’re going to tell you more about the preprocessor later, but for now we’ll only say that it’s a
separate part of the compiler whose task is to pre-read the text of the program and make some modifications in it. The prefix
"pre" suggests that these operations are performed before the full processing (compilation) takes place.

The changes the preprocessor will introduce are fully controlled by its directives. In our program, we are dealing with
the include directive. When the preprocessor meets that directive, it replaces the directive with the content of the file whose
name is listed in the directive (in our case, this is the file named  iostream ). The changes made by the preprocessor never
modify the content of your source file in any way. Any alterations are made on a volatile copy of your program that disappears
immediately after the compiler finishes its work.

So why do need the preprocessor to include the content of a completely unknown file called iostream? Writing a program is
similar to building a construction with ready-made blocks. In our program, we are going to use one such block and it will
happen when we want to write something on the screen. That block is called  cout  (you can find it inside our code), but the
compiler knows nothing about it so far. In particular, the compiler has no idea that  cout  is a valid name for that block
while  cuot  isn't. The compiler must be warned about it – it needs to be aware of the fact.

A set of preliminary information that the compiler needs is included in header files. These files contain a collection of
preliminary information about ready-made blocks which can be used by a program to write text on the screen, or to read letters
from the keyboard. So when our program is going to write something, it will use a block called cout, which is able to do the
trick (and much more). We don't want the compiler to be surprised, so we need to warn it about that. The compiler’s developers
put a set of this anticipatory information in the iostream file. All we have to do is use the file. This is exactly what we expect
from the include directive.

But where is the  iostream  file located? The answer is simple, but not as clear as you might want: that’s not our problem. The
preprocessor knows where it is. Good job, preprocessor!

#include <iostream>
using namespace std;
int main()
{
cout << "It's me, your first program.";
return 0;
}

In the C++ language, all elements of the standard C++ infrastructure are declared inside
the namespace called  std . A namespace is an abstract container or environment created to hold a logical
grouping of unique entities (blocks).

An entity defined in a namespace is associated only with that namespace. If you want to use many of the
standard C++ entities (we’re going to tell you all about them later) you must insert the  using
namespace  instruction at the top of each file, outside of any function.

The instruction should specify the name of the desired namespace ( std  in our case). This will make the
standard facilities available throughout the program.

It's worth to add (although you're not obliged to use the knowledge just know) that you may omit
putting  using namespace  in your code but the cost of such omission is non-zero. Now you have to inform the
compiler where  cout  block come from and you must do it each time you use any of the entities derived from
the  std  namespace. In other words, you need to write:

std::cout

instead of:

cout

Judge for yourself if it pays off. The compiler doesn't care what you choose. Anyway, we prefer to use  using
namespace  as it makes code clearer and more consistent.

We’ve already said something about the blocks. Now let's go a little deeper. One of the most common types of
blocks used to build C++ programs are functions.

If you associate a function with mathematics, you’re on the right track. Imagine a function as a black box,
where you can insert something into it (though this is not always necessary) and take something new out of it,
as if from a magic hat. Things to be put into the box are called function arguments. Things to be taken out of
the box are called function results. In addition, a function can do something else on the side.

If this sounds rather vague, don't worry, we’ll talk about functions many times and in much more detail later.

Back to our program. The standard of the C++ language assumes that among many different blocks that may
be put into a program, one specific block must always be present, otherwise the program won't be correct.
This block is always a function with the same name:  main .

Every function in C++ begins with the following set of information:


 what is the result of the function?
 what is the name of the function?
 how many arguments does the function accept and what are their names?

Take a close look at our program and try to read it properly, accepting the fact that you won’t yet fully
understand everything.

 the result of the function is an integer value (we can read it from the word  int , which is short for
integer)
 the name of the function is main (we know why already)
 the function doesn't require any arguments (what we can deduce from the absence of anything
between parentheses).

This set of information is sometimes called a prototype, and it’s like a label affixed to a function announcing
how you can use that function in your program. The prototype says nothing about what the function is
intended to do. It’s written inside the function and the interior of the function is called the function body. The
function body begins with the first opening bracket  {  and ends with the corresponding closing bracket  } . It
might sound surprising, but the function body can be empty, which means that the function does exactly
nothing.

We can even create a function that is lazy – it can be encoded like this:

void lazy() { }

The word  void  put in front of function's name ( main ) instructs the compiler that the function provides no
result. Indeed, laziness rarely has utilizable results so don't be surprised.

Summing up, this drone produces no result (in other words, result is void), its name is "lazy", it doesn't take
any arguments (there is nothing between parentheses) and it does absolutely nothing (there is nothing
between brackets).

By the way, the names of the functions are subject to some fairly rigid constraints. More on this later.

TIME MACHINE
It's worth to mention that previous versions of C++ preferred to use somewhat different notation to declare
the fact that a particular function (including main) doesn't accept any arguments. This is how it looked:

int main(void) {}

Note the  void  put inside the parentheses. Such a convention derived from C language where the
clause  ()  had definitely different meaning. We prefere not to stay in the past so you won't see  void  in this
role in our snippets.

Inside the main function body we need to write what our function (and thus the program) is supposed to do. If
we look inside, we find a reference to a block named  cout .

Firstly, note the semicolon at the end of the line. Each instruction (more precisely, each statement) in C++
must end with a semicolon – without it the program will be incorrect.
This particular statement says: instruct the entity named  cout  to show the following text on the screen (as
indicated by the  <<  digraph, which specifies the direction in which the text is sent). You might ask – how do we
know that  cout  will do that for us? Well, we know it because it says so in the C++ language standards.

The  cout  entity (in fact, it's an object, but we don't want to bring up this word too soon – more on it later)
must be fed with something that is intended to be shown on the screen. In our example, the feed is just text
(string). For simplicity, we can assume that strings in the program in C++ are always enclosed in quotes – that
way the compiler recognizes the text that is sent to the user of the program, and the text that is intended to be
compiled is translated into machine language. This distinction is very important. Take a look:

int main();

The line above is the main function prototype (i.e. a hint saying what can we expect from a particular
function).

"int main();"

The line above is not the main function prototype, but a string that only looks like part of a source code. The
compiler is not interested in what is between the quotes, and therefore doesn’t recognize such strings as
code.

How does it work? We can picture it like this: the execution of our main function is suspended (we can say that
the main function falls asleep) and during that time  cout , together with  <<  (this kind of symbol is
named operator) prints the text on the screen. When the text is printed, the main function wakes up and
continues its activity.

The above form of source code is the most natural and perhaps the most easily read by humans, but you’re
still free to write it in a different way. For example:

cout
<<
"It's me, your first program."
;

In the C++ language it isn’t necessary to write just one statement per line. You can place two (or more)
statements on the same line, or split one statement into several lines, but bear in mind that readability (for
humans) is a very important factor. However, compilers, unlike humans, will never complain about your style.

We’re almost at the end now. There’s only one line left in our program. This is:

return 0;

This is another (beside the function invocation) statement of the C++ language. Its name is just  return  and
that’s what it does. Used in the function, it causes the end of function execution. If you perform return
somewhere inside a function, this function immediately interrupts its execution.

The zero after the word return is a result of your function  main . It's important - this is how your program tells
the operating system the following: I did what I had to do, nothing prevented me from doing this, and everything is
okay.
If you were to write:

return 1;

this would mean that something had gone wrong, it did not allow your program to be performed successfully
and the operating system could use that information to react appropriately.

Usually, if a function declares itself as a integer value provider (like our  main  function) it's obliged to contain
the  return  statement while the  return  statement is obliged to return an integer value. Expect compilation
error if you don't see to it. It seems to be clear, doesn't it? It's not fair to promise a value and to break faith (it's
not just about functions).

However, the  main  function is exceptional. It must be declared as  int  but doesn't have to return it. Sounds
weird? Absolutely! Moreover, if there is no  return  statement inside the  main  function, compiler assumes
that  return 0  has been implicitly used. Sounds weirder? Not at all - thank to that you don't have to make
additional efforts if you're going to point that execution of your code terminated successfully.

Of course, it's a matter of taste in a measure. We definitely prefer to use  return  in  main . Your preferences
may be different.

So is that all? Yes, that’s it! Let's look again at our program and see what’s happening step by step:

 we introduced the function named main into our program - it will be executed when you start the
program;
 we made use of an entity named cout inside the main function - it will print the text on the screen;
 the program finishes immediately after printing, indicating that everything you expected to achieve has
been achieved.

So hopefully it wasn’t as difficult as it seemed at first glance. Now let’s try to persuade the computer to
compute something for us – after all, that’s what they’re for.

Numbers and how computers see them


Do you know how computers perform calculations on numbers? Maybe you've heard of the binary system and know that it’s
the system computers use for storing numbers and that they can perform any operation upon them. We’re not going to go the
intricacies of positional numeral systems here, but we will say that the numbers handled by modern computers are of two types:

 integers, that is, those which are devoid of the fractional part;
 floating-point numbers (or simply floats), that contain (or are able to contain) the fractional part.

This definition is quite simplistic, but good enough for our purposes. This distinction is very important and the boundary
between these two types of numbers is very strict. Both of these kinds of numbers significantly differ in how they are stored in a
computer memory and in the range of acceptable values. Additionally, the characteristic of a number which determines its kind,
range and application is called type.

So now we know two types of the C++ language – an integer type (known as  int ) and a floating point type (known
as  float ).

For now, let's leave the floating-point numbers aside (that’s right: more on them later) and let’s consider a question that’s maybe
a bit banal at first glance: how does the C++ language recognize the integers?
Well, it’s almost the same as when you write them on a piece of paper – they’re simply a string of digits that make up a number.
But there’s a catch – you can’t include any characters that are not digits inside the number. There is only one exception to the
rule: if you think that the number contains so many digits that it becomes ambiguous, you can insert as many single quotes
(apostrophes) inside the number. These quotes don't change the number's value and compiler ignores them completely.

TIME MACHINE
Using single quotes as separators enhancing integer numbers readability have been introduced in C++17 - don't be surprised if
an older compiler rejects such a notation

Take for example the number eleven million one hundred and eleven thousand one hundred and eleven. If you took a pencil in
your hand right now, you would probably write the number like this:

11,111,111

or (if you are a Pole or a German) like this:

11.111.111

or even like this:

11 111 111

For sure, this makes it easier to read if the number consists of many digits. However, C++doesn’t like this at all. You have to
write this number as follows:

11111111

or - if you want your number to be extremely legible - you can write it down as:

11'111'11

If you don’t, the compiler will shout at you. And how do you code negative numbers in C++? As usual, by adding a minus. You
can write:

-11111111

Positive numbers don’t need to be preceded by the plus sign, but you can do it if you want. The following lines describe the
same number:

+123

123

For now we’ll deal only with integers – we’ll introduce floating-point numbers very soon.

There are three additional conventions, unknown to the world of mathematics. The first of them allows us to use the numbers in
an octal representation. If an integer number is preceded by the 0 digit, it will be treated as an octal value. This means that the
number must contain digits taken from the 0 to 7 range only.

0123

is an octal number with a (decimal) value equal to 83.

The second allows us to use hexadecimal numbers. Such number should be preceded by the prefix written as  0x  or  0X .
0x123

is a hexadecimal number with the (decimal) value equal to  291 .

The third allows us to introduce binary numbers which are preceded by the prefix written as  0b  or  0B .

0B1111

is a binary number equal to decimal value  15 .

A variable is variable
So the C++ language allows us to write numbers. It probably won't surprise you that we can do some arithmetic operations with
these numbers too: add, subtract, multiply and divide. Contain your excitement – we’ll be doing that soon enough. But it’s quite
normal to ask how to store the results of such operations in order to use them in other operations. There are special "containers"
for that purpose and these containers are called variables. As the name variables suggests, the content of a container can be
varied in (almost) any way.

What does every variable have?

 a name;
 a type;
 a value;

Let's start with the issues connected with a variable’s name. Variables don’t magically appear in our program. We (as
developers) decide how many, and which variables, we want to have in our program. We also give them their names, almost
becoming their godparents. If you want to give a name to the variable, you have to follow some strict rules:

 the name of the variable must be composed of upper-case or lower-case Latin letters, digits and the
character  _  (underscore);
 the name of the variable must begin with a letter;
 the underline character is a letter (strange but true);
 upper- and lower-case letters are treated as different (a little differently than in the real world – Alice and ALICE are
the same given names but they are two different variable names, consequently, two different variables);

These same restrictions apply to all entity names used in C++

The standard of the C++ language does not impose restrictions on the length of variable names, but a specific compiler may
have a different opinion on this matter. Don't worry; usually the limitation is so high that it’s unlikely you would actually want
to use such long variable names (or functions).

Here are some correct, but not always convenient variable names:

 variable
 i
 t10
 Exchange_Rate
 counter
 DaysToTheEndOfTheWorld
 TheNameOfAVariableWhichIsSoLongThatYouWillNotBeAbleToWriteItWithoutMistakes
 _

The last name may be ridiculous from your perspective, but your compiler thinks it’s just great.

And now some incorrect names:


 10t (does not begin with a letter)
 Adiós_Señora (contains illegal characters)
 Exchange Rate (contains a space)

You can find more information about C++ naming style and conventions in the C++ Core Guidelines.

The type is an attribute that uniquely defines which values can be stored inside the variable. We’ve already
encountered the integer ( int ) and floating point ( float ) types. The value of a variable is what we have put
into it. Of course, you can only enter a value that is compatible with the variable’s type. Only an integer value
can be assigned to an integer variable (or in other words, to a variable of type  int ). The compiler will not allow
us to enter a floating-point number here.

Let's talk now about two important things – how the variables are created and how to enter a value inside
them (or rather – how to give them a value).

The variable exists as a result of a declaration. A declaration is a syntactic structure that binds a name
provided by the programmer with a specific type offered by the C++ language. The construction of such a
declaration (or the declaration syntax) is simple: just use the name of the desired type, then the variable name
(or variable names separated by commas if there are more than one). The whole statement ends with a
semicolon.

Let's try to declare a variable of type int named counter. The relevant portion of the program looks like this:

int counter;

What is declared by the following fragment of a program?

int variable_1, account_balance, invoices;

It declares three variables of type int named (respectively)  variable_1 ,  account_balance  and  invoices .

Remember that you are allowed to use as many variable declarations as you need to achieve your goal.

And how do we give a value to the newly declared variable? You need to use the so-called assignment operator. Although this
sounds rather mysterious, the operator has a simple syntax and unambiguous interpretation. The assignment operator looks very
familiar – here it is:
=

Let's look at some examples:

counter = 1;

The above statement says: assign a value of 1 to a variable named counter or a bit shorter assign 1 to counter.

Some programmers use a different convention and read such a statement as: counter becomes 1.

It's worth to mention now that you're are allowed and even encouraged to place the variable declaration and its first assignment
in the same place. Look: a piece of code like this:

int variable;

variable = 1;
can be compacted into the following form:

int variable = 1;

Such a solution shows some important advantages. The most valuable is that declaring variable with immediate assigning it
with its initial value is less error-prone than performing these two activities in two different places. The code is more legible,
programmer's intentions are better recognizable and if you're used to declare and initialize variable in one step you minimize the
risk of use an uninitialized variable. This is why we prefer such declarations in our code.

As usual on such occasions, a new word arrives into our vocabulary: the part of the declaration placed on the right side of
the  =  sign is called an initiator.

The initiator you saw before was a simple value, but you can also use more complex expressions, like the one below.

int twosquared = 2 * 2;

We’ll be using initiators often. They’re extremely convenient, quite useful and can be applied to virtually all C++ data types.

Another assiagnment example:

result = 100 + 200;

In this case, the new value of the variable  result  will be the result of adding 100 to 200, but you probably already guessed
that, right?

And now a slightly more difficult example:

x = x + 1;

Seeing that, a mathematician would probably protest – no value may be equal to itself plus one. This is a contradiction.

But in the "C" language the sign "=" does not mean is equal to, but assign a value.

So how do we read such a record in the program?

Take the current value of the variable x, add 1 to it and store the result in the variable x

In effect, the value of variable x was incremented by one, which has nothing to do with comparing the variable to any value.

Keywords – why they are the keys?


Take a look at the right side of the screen – you’ll see a list of words that play a very special role in every C++ language
program. They are called keywords or (more precisely) reserved keywords. They are reserved because you can’t use them as
names: neither for your variables, nor for your functions or any other named entities you want to create. The meaning of the
reserved word is predefined and can’t be changed in any way.

TIME MACHINE
Don't be surprised by the fact that each C++ version uses different set of keywords. As you probably suspects, the list grows
with each new C++ standard. The list you see comes from C++17 and some of the keywords aren't present in earlier releases.

Fortunately, because the C++ compiler is case-sensitive, you can modify any of these words by changing the case of any letter,
thus creating a new word, which is not reserved any more.
For example - you can't do this:

int int;

You can’t have a variable named  int  - it’s prohibited. But you can do this instead:

int Int;

The compiler will be happy, very happy although it's worth to emphasize that using names similar to keywords may leads to
troublesome misunderstandings. Moreover, names starting with capital letters may have very specific meanings and in general,
are not recommended for naming creations as simple as int variables. Think twice and judge for yourself whether such a name
won't look better:

int int_value;

Comments on the comments


Now we’re going to make some comments. We don't mean comments on either your achievements or our achievements,
although we’re sure you have many achievements to be proud of. We’re referring to other comments, namely comments on the
program and inside the program at the same time.

The developer may want to add a few words addressed not to the compiler but to humans, usually to explain to other readers of
the code how the tricks used in the code work, or the means of variables and functions, and possibly, to store information on
who the author is and when the program was written.

Good and responsible developers describe each newly created important entity; in particular, explaining the role of the
parameters and the values modified or returned as results, as well as explaining what the code actually does.

How do we leave something like this in the source code? We have to do it in a way that won't force the compiler to interpret it
as part of the code. The remark inserted into the program, which is omitted at the time of compiling, is called a comment.

If we want to be precise, we should say that each comment is lexically equivalent to one space. Whenever the compiler
encounters a comment in your program, the comment is completely transparent to it - from its point of view this is only one
space (regardless of how long the real comment is).

The C++ language supports two ways of inserting comments:


// comment  - single-line comments

and

/* comment */  - block comments (also knows as C-style comments due to fact that they are in use since the very beginning
of the C programming language, the C++ progenitor).

A single-line comment discards everything from where the pair of slash signs ( // ) is found up to the end of that same line.

In the C++ language a block comment is a text that begins with a pair of the following characters:

/*

and ends with a pair of the following characters:

*/

The comment can span several lines or can occupy only one line or part of a line.

Here you can see an example in which everything from the pair of slash signs on is ignored by the compiler. The single-line
comment can start anywhere on the line. This could be a blank line too, with no content at all.

int counter; // counts the number of sheep in the meadow

Look at the snippet below. Here you can see an example of a similar comment, but introduced into the code using the second
method.

Any new developer reading the program will be aware of the true meaning of the variable. The developer will read the code
faster and it’ll take less time to understand it.

/* the counter variable counts the number of sheep in the meadow */


int counter;

Developers often place a note at the beginning of the source informing when they write the program stating who amended it and
why. The note may appear like this:

/* ************************************************************
Counting sheep version 1.0
Author: Ronald Sleepyhead, 2012
email: rs@insomnia.org

Changes:
2012-09-13: Ginny Drowsy: counting black sheep improved
************************************************************ */

Note that, despite the complicated structure and the multitude of stars, the condition stating how the comment should be started
and finished is fully met.

Comments may be useful in another respect - you can use them to mark a piece of code that you currently don’t need for
whatever reason. We often do this during the testing of the program in order to isolate the place where an error could be hidden.

We’ve just got one more thing to say about comments. Compilers differ in assessing whether another comment may be placed
within a single comment. Consider the following program:
/* int i; /* int j; */ int k; */

The question is: are you allowed to nest one block comment (like  /* int j; */ ) inside another block comment?

The answer is no. Such a notation may not be accepted by a particular compiler and in effect makes our code prone to
compiler's whims - we don't want to rely on uncertain assumptions.

We strongly discourage you from use such a construction in your code even if your compiler seems to be indifferent to it.

Floating-point numbers
A word (or 2.0 words) about floating-point numbers in real life and in the C++ language.

Previously, we became acquainted with the concept of data type, and learned that one of the basic types
known in the C++ language is the integer type named int. Now it's the time to talk about another type,
designed to represent and store the numbers that (as a mathematician would say) have a non-empty
decimal fraction.

These are the numbers that have (or may have) a fractional part after the decimal point, and although this is a
very simplistic definition, it is sufficient for our purposes. Whenever we use a term like "two and a half" or
"zero point four" we think of numbers which the computer considers to be floating numbers.

Let's go back to the values we quoted a moment ago. "Two and a half" looks normal when you write it in a
program, although if your native language uses a comma instead of a point in the number, you should make
sure that your number contains points and not commas. The compiler will either not accept it or (in very
rare circumstances) will misunderstand your intentions, as the comma itself has its own reserved meaning in
the C++ language.

If you want to use a value of just "two and a half", you should write it as shown here:

2.5

Note once again – there is a point between "2" and "5" - not a comma.

As you can probably imagine, you can write the value of "zero point four" in C++ as:

.4

Don’t forget this simple rule – you can omit zero when it’s the only digit in front of or after the decimal point.
In essence you can write the value  0.4  like on the right.

For example: the value of  4.0  could be written as 4. without changing its type or value.

Note: the decimal point is essential to recognize floating-point numbers in C++. Look at these two numbers:

4
4.0

You might think that they’re exactly the same, but the C++ compiler sees them completely differently:
4  is an int.

4.0  is a float.

We can say that the point makes a float. Don't forget that.

When you want to use any numbers that are very large or very small, you can use so-called scientific notation. Take, for
example, the speed of light expressed in meters per second. Written directly it would look like:

300000000.

As you probably suspect, you're also allowed to write the value in a more legible form:

300'000'000.

as the single quotes can be used inside floats either.

To avoid the tedious job of writing of so many zeros, physics textbooks use an abbreviated form, which you’ve probably seen
already:

3 • 108

It reads: "three times ten to the power of eight"

In the C++ language, the same effect is achieved in a slightly different form – take a look:

3E8

The letter E (you can also use the lower case letter e – it comes from the word exponent) is a concise version of the phrase
"times ten to the power of".

Note:

 the exponent (the value after the "E") has to be an integer.


 the base (the value in front of the "E") may or may not be an integer; in other words, not only dot makes float
- E (even alone) can do it too.

 Let's see how we use this convention to record numbers that are very small (in the sense of their
absolute value, which is close to zero). A physical constant called Planck's constant (and denoted as h)
has, according to the textbooks, the value of:

 6.62607 x 10-34

 If you would like to use it in a program, you would write it this way:

 6.62607E-34
Let's go back to the floating-point values. We already know what a variable is, and we also know how to declare an integer
variable, so now it’s time to declare variables of a floating-point type.

We do this using the keyword  float . Knowing that we can declare two floating-point variables, named  PI  (we can't name
it  Π  because - as you already know - the C++ language freaks out when variable names are written with Greek letters)
and  Field :

float PI, Field;

As you can see, the difference in declaring the integer and float variables is quite small from the syntax's point of view.

This difference in terms of semantics is significant, as you can see in the example below. With a little thought, we can figure out
that the symbol (more precisely - the operator) that performs the mathematical division is a single character / (slash). Take a
look at the code:

int i = 10 / 4;
float x = 10.0 / 4.0;

It might be a bit surprising for you to know that the value that will be entered in the variable  i  is  2  (yes - just  2 !) while the
variable  x  will be equal to  2.5 . Look at the example carefully, because it illustrates a very important difference between these
two data types.

What happens when we have to convert integer values into float values or vice versa? We can always
transform from  int  into  float , but it can lead to a loss of accuracy. Consider the example below:

int i = 100;
float f = i;

After changing from  int  to  float , the value of the variable  f  is  100.0 , because the value of type  int  ( 100 ) is
automatically converted into a  float  ( 100.0 ).

The transformation affects the internal (machine) representation of those values as computers use different
methods for storing floats and ints in their memory.

Let's consider the opposite situation now.

As you’ve probably guessed, these substitutions will result in a loss of accuracy - the value of the variable  i  will
be  100 . Twenty-five hundredths has no meaning in the ints world. Furthermore, converting a  float  into
an  int  is not always feasible.

Integer variables (like floats) have a limited capacity. They cannot contain arbitrarily large (or arbitrarily small)
numbers.
For example, if a certain type of computer uses four bytes (i.e. 32 bits) to store integer values, you can only use
the numbers from the range of -2147483648 to 2147483647.

Let's consider the following snippet:

float f = 1E10;
int i = f;

The  i  variable is unable to store such a large value, but it isn’t clear what will happen during the assignment.
Certainly a loss of accuracy will occur, but the value assigned to the variable  i  is not known in advance.

In some systems it may be the maximum permissible  int  value, while in others an error occurs, and in others
still the value assigned can be completely random.

This is what we call an implementation dependent issue. It's the second (and uglier) face of software
portability.

Operators
An operator is a symbol of the programming language, which is able to operate on the values. For
example, an assignment operator is the  =  sign. We already know that it can assign values to variables.

Now let’s look at some other operators available in the C++ language and find out which rules govern their use
and how to interpret the operations they perform. Let’s begin with the operators associated with widely
recognizable arithmetic operations. The order of their appearance is not accidental. We’ll talk more about this
afterward.

Multiplication
An asterisk  *  is a multiplication operator. If you take a look at the code here, you’ll see that the
variable  k  will be set to the value of  120 , while the  z  variable will be set to  0.625 .

int i = 10, j = 12;


float x = 1.25, y = 0.5;

int k = i * j;
float z = x * y;

Division
A slash (" / ") is a divisional operator. The value in front of the slash is a dividend, the value behind the slash,
a divisor. Look at the snippet of the program below: of course,  k  will be set to  2 ,  z  to  0.5 .

int i = 10, j = 5;
float x = 1.0, y = 2.0;

int k = i / j;
float z = x / y;
Division by zero
As you’ve probably guessed, dividing by zero is strictly forbidden, but the penalty for violating that rule will
come to you at different times.

float x = 1.0 / 0.0;

If you dare to write something like that, the compiler will go nuts – you’ll get a compilation error, runtime error
or some message at runtime, possibly also a few choice words about your programming capabilities. OK, the
last one was a joke. Still, in some cases you won't be able to run your program. As a general rule, you
shouldn't divide by zero.

In the following example the compiler won't tell you a thing, but when you try to execute that code, the result
of the operation may be surprising. It’s not a number. It’s a special featured value named  inf  (as in infinitive).
Generally, this kind of illegal operation is a so-called exception.
float x = 0.0;
float y = 1.0 / x;

When you find exceptions in your program, you should react accordingly. We’ll discuss this later.

Addition
The addition operator is the " + " (plus) sign, which most of us already know from maths class. Again, take a
look at the snippet of the program – as you can surmise,  k  is equal to  102  and  z  to  1.02 .

int i = 100, j = 2;
float x = 1.0, y = 0.02;

int k = i + j;
float z = x + y;

Substraction
The subtraction operator is obviously the " - " (minus) sign, although you should note that this operator also
has another meaning – it can change the sign of a number. This is a good time to show you a very important
distinction between unary and binary operators (in the C++ language there is also a ternary operator –
more on that a bit later).

As usual, let’s get acquainted with a snippet of the program – you can guess that  k  will be equal to  -100 ,
while  z  will be equal to  0.0 .

int i = 100, j = 200;


float x = 1.0, y = 1.0;

int k = i - j;
float z = x - y;
Unary minus
In "subtracting" applications, the minus operator expects two arguments: the left (a minuend in arithmetic
terms) and the right (a subtrahend). For this reason, the subtraction operator is considered one of the binary
operators, just like the addition, multiplication and division operators. But the minus operator may be used in
a different way – take a look at the snippet.

int i = -100;
int j = -i;

As you’ve probably guessed, the variable  j  will be assigned the value of  100 . We used the minus operator as
a unary operator, as it expects only one argument – the right one.

Unary plus
The same dual nature is expressed by the " + " operator, which can be also used as a unary operator – its role is
to preserve the sign. Take a look at the snippet.

int i = 100;
int j = +i;

Although such a construction is syntactically correct, using it doesn’t make much sense and it would be hard
to find a good rationale for doing so.

Remainder
The remainder operator is quite peculiar, because it has no equivalent among traditional arithmetic
operators.

Its graphical representation in the C++ language is the  %  (percent) character, which may look a bit confusing,
although you have to admit that its appearance resembles the  /  operator which is responsible for the division
while finding the remainder forces the computer to perform a division.

%  a binary operator (it performs the modulo operation) and both arguments cannot be floats (don't forget
that!). Look at the example:

int i = 13;
int j = 5;
int k = i % j;

The  k  variable is set to the value of  3  (because 2 * 5 + 3 = 13).

Oh, and one more thing you need to remember: you cannot compute the remainder with the right
argument equal to zero. Can you guess why? Click Check below to see if you were right:

Check
You probably remember what we said earlier about dividing by zero. And because division by  0  invokes undefined behaviour,
the modulo operation, which relies on division, is undefined, too.
Well, that’s what the C++ Standard says. We have to accept that.

Priorities
So far, we’ve treated each operator as if it had no connection with the others. Of course, in real programming,
nothing is ever as simple as that. Also, we very often find more than one operator in an expression and then
things can get complicated very quickly. Consider the following expression:

2 + 3 * 5

If your memory hasn't failed you, you should remember from school that multiplications precede additions.
You probably remember that you have to multiply  3  by  5 , keep the  15  in your memory, add it to  2 , thus
getting the result of  17 .

The phenomenon that causes some operators to act before others is known as the hierarchy of priorities.
The C++ language precisely defines the priorities of all operators and assumes that operators of larger
(higher) priority perform their operations before the operators with lower priority.

So if we know that  *  has a higher priority than  + , we can figure out how the final result will be computed.

Bindings
The binding of the operator determines the order of computations performed by some operators with equal
priority, put side by side in one expression. Most operators in the C++ language have the left-sided binding,
which means that the calculation of this sample expression is conducted from left to right, i.e.  3  will be added
to  2 , and  5  will be added to the result.

2 + 3 + 5

Now at this point you might be snorting and saying that all children know perfectly well that addition is
commutative and it doesn’t matter in which order the additions are performed. And yes, you're right, but not
quite. Additions performed by the computer are not always commutative. Really. We’ll show you this in more
detail later. But for now, be patient and trust us.

Priorities
Since you're new to C++ language operators, presenting a complete list of operators' priorities may not be a good idea. Instead,
we’ll show you its truncated form, and we’ll expand on it consistently during the introduction of new operators.

This table now looks as follows:

+- unary
*/%
+- binary

Note: we’ve gone through the operators in order from the highest to the lowest priority.
We want to check if you understand the concept of binding. Try to work through the following expression:
2 * 3 % 5

Both operators ( *  and  % ) have the same priority, so the result could be guessed only when you know the binding direction.

Do you know the result? Click Check below to see if you were right:

Check
1
Yes, the result is 1. Congratulations!

Parentheses
Of course, we’re always allowed to use parentheses, which can change the natural order of calculation. Just
like with arithmetic rules, subexpressions in parentheses are always calculated first. You can use as many
parentheses as you need and we often use them to improve the readability of an expression, even if they
don't change the order of operations.

An example expression involving multiple parentheses is given below. Try to compute the value given to
the  l  variable.

int i = 100;
int j = 25;
int k = 13;
int l = (5 * ((j % k) + i) / (2 * k)) / 2;

Click Check below to see if you were right:

Check
10
Yes, it's 10.

Operators continued
Here are some operators in the C++ language which you won’t find in maths textbooks. Some of them are
frequently used to increment a variable by one. This is often done when we’re counting something (e.g.
sheep). Let's consider the following snippet:

int sheep_counter = 0;

Every time a sheep runs through our thoughts we want the variable to be incremented, like this:

sheep_counter = sheep_counter + 1;
Similar operations appear very frequently in typical programs, so the creators of the C++ language introduced
a set of special operators for these actions. One of them is the  ++  (plus plus) operator. You can achieve the
same effect in a shorter way:

sheep_counter++;

It looks much more elegant now, doesn't it?

You might also like