Category Archives: The basics of programming in C ++

In this section of our site merged articles, who cover the basics of programming in C ++ for beginners

Working with localized strings




first, you need to be able to do with the localized strings - a record character constants broad localized characters and distinguish them from conventional lines char[]. For this line is written to the prior s qualifier L:

The result will be:

Pay attention, the string length (number characters) in this case, clearly less, than the number bytes allocated for the string (your operating system, their attitude may be different from, I show in Linux, but it does not affect the programming technique).

In such a line near with equal success may be symbols of diverse nature: different languages, special mathematical symbols, common in theirske designation of the Greek alphabet (a, e, i, Fr., p, l, Phi, Oh ...), musical notes, etc.. How are you, obviously, know, just as well as a part of wide character strings, with equal success, and can meet the characters of the Latin alphabet (ASCII main table), with each such symbol will also hold 2 or 4 bytes (depending on the agreements adopted in the operating system), in contrast to the usual 1 bytes.

We perform a number of operations with the Russian lines, but writing them (till) in traditional form arrays char:

perform:

It would seem, what (nearly) everything is working precisely a textbook, and why do we need any extensive localized strings? But this deceptive illusion! The point here is, that some traditional functions lowercase (strcat(), strcpy(), strdup(), strstr() and etc.) will return the correct results. Это потому что они выполняют операции над байтами, byte by byte, without delving into the internal structure of characters to copy.

But other operations (and false результат strlen() it has clearly points) will not work properly: strncpy(), strchr(), strsep(), strtok() and etc. And они будут создавать вам очень неожиданные результаты, very difficult to interpret. Lookthey how to work byte string Reverse, and how to distinguish his work on the English and Russian line:

It works so, и это определённо not that, what you expected to receive:

nand this concludes our discussion of the possibility of representing the Russian-speaking lines of traditional arrays char[] and the processing of their traditional functions in lower case, and complete this examination output: _y to earn with Russian lines as an array char шt is possible only:

and). or when we use string constants unchanged, only as a line for their input-output unchanged;

b). or for the treatment of their functions (library or their own), which do not take into account the internal structure of the characters, without delving into the is contentit is strings, and operate with them simply as a meaningless sequence of bytes.

In all Otherwise correctI работа с кириллицей available only as a broad array of localized characters wchar_t (with completingm строку широким нулевым символом L’′). To work with localized representation of lines of C library provides wide a set of line features, completely similar to the traditional functions of the lower case, but instead of the prefix str in their names prefixed with wcs: wcslen() instead strlen(), wcsncpy() instead strncpy() etc.

Let's see how it works on the example of:

This illustration is quite enough, to see direct analogies manipulation functions with symbols wchar_t. the, who has some experience working with strings char effortlessly spread it wide strings. Setting language locale (call setlocale()) O devices (terminal) obligatory, because the C / C ++ program sets the default locale “C” (andto historically), which allows output only 128 characters younger half of the 8-bit ASCII characters.

In the illustrated writing function sets the locale, used in the default operating system - I'm guessing, that we are experimenting in the Russian-speaking the installed system. The new language standard (C99) and introduces a new format for the string formatting functions (printf(), sprintf()) %ls, This format strings wchar_t[].

Tinternally as well, As with arrays char, converts to C ++ from C, C ++ library introduces a complete analogue of the container class string, but containing in their composition wide localized characters, and is known as the class wstring:

Here, the output string of localized characters (ws) must is output to the output stream wcout (similar in meaning cout, but other than cout).

In the illustrated writing: locale::global( locale( “” ) )This locale setting by default in C ++ OOP way, similar to, as it has been shown before in the manner of C.

Atpolls IO wide character strings (to the terminal or to a file) separate complicated subject, therefore consideration will be deferred to a single note on this subject.

Newsletter of programming:

Localization of character strings




Localization of character strings in c ++

The vast number of code samples with C / C ++ strings (in any published sources) It operates with zero-terminal arrays (ASCIZ) elements char (in the style of C), or container type string (in the style of C ++), built as an add-on such arrays. All of this works wonderfully with strings Latin (English) characters, but can go racing on lines, containing symbols of foreign language alphabets (Russian, Chinese, Arabic and Hebrew). There is not that simple ... and very poorly described in the literature, that is understandable: English-speaking authors pay little attention to questions of foreign language localization, and domestic authors, in the majority, rewriting and adapting the English-language publications, do not pay attention to this aspect of the question.

C language - a very old programming language, and C ++ inherits from it formats and constrained by the requirements of syntactic compatibility with C. In order for the, not to have a C / C ++ problem with such lines (called localized) you need to understand what's going on with these localizations ...

Historical, symbols (char) submitted (1963 year) ASCII standard as younger 7 bits of one byte, while senior 8th bit intended for error control, occurred during data transfer. This encoding allows you to encode all possible 128 different symbols, and this number is hardly enough to the characters of the English alphabet (big and small), digital (code 0x30-0x39), managers (less code 0x20) and special characters. When it comes to the submission of national alphabets, type the alternate character table, such as KOI-7 for Russian language. Switching to a stream input-output table for alternative symbol by symbol with code 0x18 (code is called: Device Control 2) in the stream, and return to the ASCII main table - the symbol with code 0x17 (Device Control 1).

Later, since the mid 80s, with time IBM PC widespread and replace them other families of computers, ASCII standard was extended by the 8th bit byte char, byte could represent 256 characters: junior 127 represents the original ASCII table (with Latin script), and older - national alphabet. But, since the national alphabets may be diverse, is to support each of them was required to enter a code page, for example, for the Russian language, this might be the page CP-866 (MS в), CP-1251 (в Windows), No-8r (в UNIX, Linux) - and each of these pages is offering its, characterized by other, the order of Russian characters. When this, for correct display (or decoding) any localized character string it is necessary to know the code page in which it is presented.

In order for the, to put an end to this Babel of language code pages, was offered (1991city) representation UNICODE standard, in which the coding system, each character is coded 32-bit value (4 bytes, but not all 32-bit values ​​are valid). This standard allows you to encode a huge number of characters of different writing systems. Documentation, encoded UNICODE standard, may comprise a single text Japanese and Chinese characters, Latin letters, Cyrillic, Greek alphabet (a, e, i, Fr., p, l, Phi, Oh ...), mathematical symbols, musical notation, musical symbols, symbols extinct, rare, exotic peoples. There is no need to switch the code page. For example, Here are the some of the symbols of language, designated as “singaliskii”:

The first UNICODE standard was released in the 91 th year. Last at the moment - in 2017 and he describes 136755 different symbols.

But UNICODE - is still only standard representation of each character. To represent this character in a particular operating system (or the programming language) need more character coding system UNICODE.

  • encoding system is widely used:
    UTF-32 - used to represent each character 4 bytes, direct numerical value UNICODE code
  • UTF-32 - to represent the most commonly used symbols used 2 bytes (first 65536 positions), and the rest are in the form of a "surrogate pairs". This encoding is used on Windows operating systems starting with Windows NT.
  • UTF-32 - to represent each character uses a variable-length sequence of bytes: from 1 byte for the ASCII characters of the main table, to 6 byte for rarely used characters (Russian alphabet characters are encoded with 2 bytes). This encoding was created later than other operating systems for Plan 9 and Inferno in 1992. Ken Thompson and Robert Pike with colleagues, and it entered as a single and bulk encoding of character strings in later Python programming languages ​​and Go. This encoding is used, Today everywhere, in the POSIX / UNIX operating systems, Linux.

Returning to the, that C / C ++ old family of programming languages, to represent them in localized characters necessary to introduce a new data type - wide characters wchar_t instead of char (the type of data appeared in the C89 standard, but, fully with API support, Only in the C99 standard). Instead of line C of the form library functions str *() for wide offer their full counterparts, but as wcs *() (instead of the prefix prefix str write wcs). Different systems may have different wchar_t bit (in Linux is int32_t, в Windows int16_t) but for a programmer that does not matter and does not create differences.

For work and converting multi-byte sequences recorded in UTF-8 encoding in C / C ++ introduced family of functions mb *(): mbtowc(), mblen(), mbstowcs(), wcstombs() and etc. It is a mechanism for mutual conversion between char array[] (which also expressed UTF-8 strings) и wchar_t[]. If you are not faced with UTF-8 encoding (that likely occurs in Windows), then this group of functions you should not take.

Similarly,, instead container class C ++ string class introduced a similar container wide characters wstring.

Specifically about the technique of Wide localized strings will be discussed in the next article. In the meantime, the 1st elementary example ... without comment - as an occasion for reflection (note and explain, that calling strlen() in each case gives the number of bytes in a string is not consistent visually apparent number of letters in it):

P.S. With great detail about the localization in C / C ++ and the localized strings, who are interested in more detail, can be read here: Language localization of the C / C ++ Language localization of the C / C ++ - there is an explanation more 22 pages of office document formats.

Newsletter of programming:

sqrt() - Cmath function library




sqrt( value );

The function sqrt() cmath library (math.h) It takes the value parameter and returns the square root.

If the ( in our case – value) negative, an error.

The result is shown in the run online compiler ideone

example of the function sqrt c ++

Newsletter of programming:

Online компиляторы




Often there is a need to quickly show someone, how to solve a small problem on programming or how to implement the algorithm. You can just throw back a piece of code, but it is better to use one of the online-compilers. Many of them have the opportunity to receive a special reference to the compiled code. This link can be to leave such comments to articles. After going through it people will see not only the code, but also the result of the work program.

Consider a few options online-compiler supports the C ++ programming language

1. Online compiler for C ++ on primat.org site . Add the code, click RUN and wait for execution.

online-compiler primat.org

If in the course of the work program requires user action – perform their:

online-compiler - user actions

If there are errors, they are displayed in the compilation tab, which opens automatically. In the contribution options, you can choose a variety of options for the compilation, if you do not like the default.

To get a reference to the code – Hit

online-compiler - user actions

Just on this site there are the compiler for Pascal.

2. ideone online-compiler

ideone online-compiler

Right at the entrance to pay attention to the programming language, which is selected by default. Change it if necessary. Incoming data to make stdin:

ideone online-compiler

ideone online-compiler

Here a very large selection to compile languages:

programming languages ​​ideone

3. Online компилятор wall box

Wall box online компилятор

Incoming data is necessary to register in order to Stdin, clicking Run.

Wall box online компилятор

I like it, he keeps a history compilations. In addition to C ++, there is a wide variety of programming languages ​​to compile:

programming languages ​​Wandbox

4. C/C++ Online Compiler

online-Compiler Compiler

online-Compiler Compiler

In the latter somehow confuse with reference to their. Plus it is not clear where to watch the result of the program. Just shows, the program returned value 0.

See also how to install Microsoft Visual Studio 2015 Express

Newsletter of programming:

pow() - Cmath function library




pow(a, b);

Функция pow() cmath library takes two parameters: a, b. The first number is a (basic) raised to the power b.

Returns the value of ab .

Execution result 23 , 53, 52 :

pow () - function of cmath library

 

Newsletter of programming:

fma () – function of cmath library




fma(a, b, c);

Function fma() of cmath library accepts three parameters: a, b – ​​for multiplying this values , c – to add value.

Returns the value of a * b + c.

Execution result ( 2 * 2 + 3):

fma () - function of cmath library

Newsletter of programming:

Installation Microsoft Visual Studio 2015 Express (IDE).




Microsoft Visual Studio development environment – this is such a special program in which we will write command PC, and she will translate these commands (using so-called compiler) to machine language (of ones and zeros), handle and throw us some results of our code. To set up Microsoft Visual Studio Express you have to pass on this link. Scroll down and find the block with the Express for Desktop – that's what we need.установка Microsoft Visual Studio Express

Note: Now Microsoft recommends that you install Visual Studio Community. If you want to install it on the same page.

Only, before clicking the Download button, check the points System Requirements (system requirements for your computer). If they do not meet your, for example you have an older version Windows, then search the Google Microsoft Visual Studio 2010 Express или Microsoft Visual Studio 2013 Express and select the version, which will be able to work properly on your computer. Well, if all requirements are met – click Download.

как установить Microsoft Visual Studio 2015 ExpressA little forward, wdexpss_full_RUS.exe file uploaded yet you can find it in the downloads on your computer. Click on it twice and press the Run button:

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Fig.2

If this happens, that you are not a happy owner of Internet Explorer 10, you will see a warning:

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Figure 3

Feel free to press the Continue. Next you have to choose which disk will be installed (can leave, that offer default). Press Set.

как установить Microsoft Visual Studio 2015 Expressм
Installation Microsoft Visual Studio 2015 Express – Fig.4

Now have to wait who how many meted out. For those who have SSD – minutes 15, a hard disk take minutes 30 – 40. So you have a little free time. You can relax.

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Fig.5

After, how everything will be adopted and enforced, we will see a message:

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Fig.6

Then all it installs without problems and can immediately start the program. You will be offered to enter the Microsoft account. If you do not have it – press Registration. It is better to immediately register, because if you do not, then through 30 days MVS 2015 Express no longer work, until you create this account.

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – Fig.7

After logging in, or check, we finally see the opened development environment. To make sure, it works fine (and it cannot be otherwise), I will show you how to create a new project, to make the code and run. In the opened MVS click New Project

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Fig.8

In this window, click on the Visual C ++, Win32, Win32 Console Application, enter a name for your new project and uncheck the create directory for solution. Click OK.

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – Fig.9

Application Wizard will open . Click Next

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – Fig.10

note Console Application and Empty Project. Next, you can click Finish.

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – Fig.11

The project created. Now in it we need to create a file with the extension .cpp. In it we will write code. This is done so: in the Solution Explorer window, right-click on your project name (I have this ConsoleApplication2)

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – Fig.12

Click Add Class and:

create a project and files cpp in microsoft visual studio

Open Visual C ++ tab and select C ++, and then in the list of templates in the central area, select the C ++ class. Click Add.

create a project and files cpp in microsoft visual studio

In the wizard, C ++ generic classes, type in the name of the class mycode. Do not change the file names and default settings. Click Finish.

create a project and files cpp in microsoft visual studio

It is all – now created a file in your project, in which commands may be written in C ++.

create a project and files cpp in microsoft visual studio

And, for convenience of work, I suggest you immediately include the numbering of lines of code. To do this click on tools – Options – Text editor – C/C++ and select line numbers. ОК.

Установка Microsoft Visual Studio 2013 Express
Installation Microsoft Visual Studio 2015 Express – рис.15

Further, without going into details, simply copy the code below and paste it into your file with a name mycode.cpp. (All that was contained before it can be removed)

After insertion, press Ctrl + Shift + B – will begin compiling a program. You should see the bottom line of the window assembly: successfully: 1, with errors: 0 etc. Then press Ctrl + F5 and see the message in the window that opens: “We created the first draft in MVS2015”.

как установить Microsoft Visual Studio 2015 Express
Installation Microsoft Visual Studio 2015 Express – Fig.16

Hope, you will succeed. If you have any questions feel free to ask them in the comments to this article.

There are also many online компиляторов that you can use for simple programming tasks.

Pointers to functions





a pointer to a function, c ++, Programming for beginners, c++

It has been observed, that the pointers can point to a variety of types of objects in the program language C ++. More precisely, to all and on all kinds of objects, Data in the program are.

However, the same objects, as conventional data objects, are functions in a Programme. Hence arises a desire to try to define and use a function pointer. Create this simple program (ex1.cc):

Here, with the function area() all clear: it calculates the area of ​​a circle of radius, who is devoted to her, as a parameter. But later, we declare a variable pointer to a function:

At the time of this announcement, the pointer pfunc It is nothing more, as a certain address in the internal computer representation (4 Byte 32-bit operating system,, 8 Byte 64-bit operating system,). This is exactly the same kind of internal, which has, let us say, a pointer to an integer variable int*. However, this index has a strictly defined type: a pointer to a function, takes one parameter of type double, and returns a value of type double. But on what specific function pointer points, at its definition - no matter: the index value is not defined.

But the next assignment operator we bind a function pointer to a particular function area(). Absolutely correct would be to record the assignment of function pointer addresses: pfunc = &area. But the C ++ compiler is smart enough, that references the function name in the assignment statement interprets as its address. Thus entry pfunc = area also absolutely correct. From this point we can use the pointer pfunc to call a function to which it points. To do this, we write the value to which the pointer points *pfunc (operation * in this context it is called dereference pointer). The parentheses around the dereferenced value pfunc in recording (*pfunc)( r ) necessary for reasons of priority of operations in terms of disclosure. Executing this example:

a pointer to a function, c ++, Programming for beginners, c++

While the use of function pointers did not bring anything fundamentally new in this example,, apart from some syntax intricacies. But in this example, we still only know how to define and use function pointers. And now we can move on to the question of why it is needed and how we can use it.

Supposing, for a large project, we are preparing a series of tests, performed in the process of development and growth of the test project (the so-called test development technology, and very productive). The number of turn-based test in this situation will continue to grow as we move readiness of the base project.

In this situation, we can do so (ex2.cc):

And that's what we have on the performance of:

a pointer to a function, c ++, Programming for beginners, c++

In this listing tests[ ] – this is array function pointers with no parameters and no return value. Beautiful solution, is not it? We can not hesitate to add new features caused by solid test, and all of them will be called in sequence when performing.

We can go even further: if the function is a pointer to a function in an expression, You can pass a function pointer as a parameter to another, embracing function, and the latter will perform in your body function to pass parameters, not knowing what action is performed at the same time.

To illustrate what has been said the program will create the most primitive calculator, performing arithmetic operations on integer operands (ex3.cc):

It performs the actual calculation function calculate(). But she did not "know" anything about the actions carried out and all arithmetic operations: it applies to the 2nd the first one of its parameters 6 functions, which she handed over to the 3rd parameter to perform.

Who does not know about typedef read here.

This code function strtod() – a standard feature of the C library (ANSI C, standard POSIX), which extracts a decimal number from a string, obtained from the standard input stream. In the context of our discussion is interesting because, what:

  • a C ++ program can use the entire set of C library calls;
  • C ++ program using runtime shared C library (.so or .dll), and in the absence of a standard C library, C ++ programs are inoperative.

But back to the calculator shown (its extremely simplified due to the fact, that we do not deal with the problems of input, its format and do not process the user input errors – in real applications so you can not do):

a pointer to a function, c ++, Programming for beginners, c++

Observant reader might have noticed, that the function calculate() despite all their desire and could not perform any of the required arithmetic operations, well as performing these actions function sum(), dif(), I have() and div() described later functions calculate() not visible in the function code calculate().

In this way, We looked at several different occasions, when functions are used in C ++, as data items. They can be combined in arrays, integrated as fields structures, or transferred to other functions as arguments. All these details and possibilities are realized at the expense of function pointers (Although they may not look as pointers syntax records, due to the intelligent C ++ compiler, who understands the context, that should be used functions addresses).

If you do not understand something on the material or the code programs – ask questions in the comments.

We invite you to evaluate this lesson and lesson Pointers to objects:

Newsletter of programming:

Conversion types




type conversion c ++, for beginners, for Dummies, from scratch, основы программирования c  Type conversion in C ++ rather old, or rather a classic operation. In short and in Russian: Conversion type – it is considered an indication of a set of computer bytes integer or real. Or a pointer to a specific class.

At all, to understand the type conversion is necessary to consider the mechanism and structure variables. For example, PAC line integer multiple: short int, int, long int, not counting the unsigned. And computer places for them a different number of memory cells (bytes): 1, 2 and 4 respectively. Convert within these types of one class is called the standard conversion. at:

Take the next: take the two younger byte of a variable "a", simply transplanted in two bytes of variable «b». Since the value in and (unit) it is currently placed in these two bytes, the program will give the correct result, and C ++ will not be against such a conversion.

Why do I need to consider the size of the variable in the conversion?

What happens if you put in a variable "a" number 123456789? It is perfectly fit in 4 byte type int, but 2 byte type short int it no longer falls. too much. С , as expected, it just cuts the long number, taking only the tail of it, and put into a variable «b». We obtain course nonsense. And with a minus, if you bring it to the screen. Converting from the variable, which occupies a greater number of bytes in the memory will not be correct. If you convert the contrary from the short in long for example such problems will not, because the bytes in the variable recipient longer, and places data that stores short quite enough.

It is necessary to know. Teachers often catch students on this focus, especially in the training manual giving a similar pitfall with variable poorly compatible with each other in size.

As for the types of real conversion, It is engaged in a math coprocessor. There is no longer just the bytes distilled from cell to cell, and special instructions are executed, which convert the whole into a type of material with a mantissa and exponent, as it should be, and return value. This is not a conversion, it is converted. Anyway, It will deal with the processor.

In this example, the math co-processor converts the real to integer, and will drive to a variable, and then do the reverse operation: It will drive a whole in his special register (It called ST), and after he would get from a real integral part, equal to that, that in variable “and”.

If you want to convert from a real double (8 bytes) in float (4 bytes), here such problems, as a whole will not be a. Math coprocessor just round up to the real value, fits in 4 bytes, that does not lead to an incorrect value:

The result will still be the number 1.234568e + 18, which means a 1.2-plus 18-degree. Another thing, what in “a” there will be rounded to the number of the 6th decimal place, instead 1.234567891234566e + 18. In general, inaccurate calculations it does not interfere, but it is recommended to use the program material of the same type, that did not happen here such rounding.

In addition to the type of transformation there is such a thing as the cast.

Visibility typecast can show such an example:

If the conversion – this decision C ++ (or rather compiler), in what type of result, it uses a type cast, rigidly specified by the programmer. In this example, the programmer tells the compiler, you need to convert it into a int, but not in short int. After all 25 and placed in int and short, that selects the compiler programmer may not know.

In everyday life such type conversions actually rare. And it's not necessary. The ideology of programming in a residential hints to avoid such frills, because they can be a rake (in the above example in the conversion of whole), therefore casts in C ++ should not be used everywhere.

:) Thank you for this article its author Stilet – Super Moderator programmers offline ProgrammersForum.

Newsletter of programming:

Exceptions in c++





exceptions in c ++, c ++ exceptions, Programming for beginners

Sometimes, during the operation of applications, there are situations that hinder further their normal work. For example, by dividing the number of zero, the program will work in spite of the fact, How many user worked in the programme, and how much data is made. The program simply closes. And imagine, if brought before the user program data and a few hours spent calculations. In such an emergency closure of the program, all the data and calculations will be lost. Agree – not very nice. May also meet this situation, when a program is trying to open is not available at this moment file, or request more, than available memory.

This kind of situation, programmers must try to anticipate and build programs, that they are able to respond flexibly to, rather than emergency close. In my favorite book The C ++ language programming. Lectures and exercises From the author. Prata, given the following definition of exceptions in C ++:

exceptions in c ++, c ++ exceptions, Programming for beginners

To you it is not difficult to understand the mechanism of exceptions in c++, Let's take a simple example. In it, we foresee the case, that at some point during the program calculations, can meet on the division of 0. Type and compile the code, located below the. To make sure, how the program responds to this situation, enter the number of 0 in a variable num2 (it acts as the divider in the example).

Because the variable var is 3, loop while, in normal situation, must work three times. With each step of the loop var decremented via decrement. But as we just have value 0 in a variable num2, the program does not take place before the end of even the first step of the loop. It will break.

The following listing, we will correct this omission – add a few components, to help respond to this situation without interrupting programs. Namely:

  • block try or try-block (attempt, sample);
  • exceptions generator – block throw (handle, run);
  • exception handler, which it intercepts -command catch (to catch, catch)

How does an exception? – The programmer registers in the code (in try-block) specific condition, what if the variable num2 will be equal to 0, in that case you need to generate an exception throw. Further, what generated throw, intercepts catch-block (as a function of the parameter) and the program will execute the code, which is registered in this block.

Example:

Understand in detail. In strings 21-29 unit is try. You must place the code, which can lead to irreversible errors. Even before the arithmetic expression dividing the set condition: if num2 will be equal to 0, then let throw generates a number 999 (for example). In that case, immediately after generating a number, further commands in the block try will no longer be performed, and the sheer number “fall” in block catch (as a parameter). Next, execute the, as indicated in block catch – in our case, this is an error message:

cout << "Ошибка №" << thr << " - division by 0!!!" << endl;

and the program will execute the following commands. In that case, if the number of num2 != 0, then throw nothing generates and catch-unit does not work.

Look now, how to react to the program, if you type num2 equal to zero. Run the program.

exceptions in c ++, c ++ exceptions, Programming for beginners

As you can see, where there could be an error and the early completion of the program, we saw a message Error №999 – division by 0!!! Program “leaped” through the division operation on 0 and fulfilled catch-block.

To help you better understand, as the value generated throw intercepts catch-block, replace the code in strings 21 – 33 on this:

In this example,, if num2 equal to 0, throw generates a string, and not the number. String “falls” in catch-block and displayed on screen.

Let's look at an example, when an exception is generated functions, divides one number by another number:

To the exclusion worked properly, this feature is necessary to call in the block try:

catch the number of intercepts 99, and dividing by 0 not be held.

Main, what you need to remember about exceptions in c++:

  • At try-block (retries block) you must place the code, which could potentially lead to the closure of the emergency program;
  • An exception is generated at block throw. If throw work program will automatically proceed to the execution of commands catch-block, ignoring the rest of the code in try-block;
  • The trap block – catch-block, intercepts the, that generates a block throw. He must be under try-block. Nothing should be written between them;
  • catch-unit does not work, if the exception were not generated. The program will simply ignore it.

To support our site – click on the piggy bank. You will be asked to send an SMS. The sum of the – your choice.

Newsletter of programming: