Category Archives: Functions, Recursion, Area of visibility of variables

В этой рубрике собраны статьи о функциях, рекурсии, области видимости переменных в языке программирования C++

Area of visibility of variables (part 2)

c++, local and global variables, the scope of variables, c ++ beginners, namespaceYou were introduced to the first article on the topic Local and global variables. Area of visibility in C ++. I would like a little more to complement her. Namely example namespaces. I wrote a prefix is ​​not in vain std:: before the output statement cout. and endl. It is also one of the formations area of visibility – namespace. If you do not go into specific details, namespace, is a certain group of operators / function / variables / types, united in this Statement “fraction” With name std.

std namespace of the header file (header in our) iostream. cout, cin, endl and etc. – it's all “dynasty” std. If you do not plug it into the code and write std:: before these operators, C ++ will tell “bye Bye”. Because he does not know, what is this cout so without “surname”. By the way in C ++ and coined the operator using namespace, which allows you to write the name of the space as a prefix to each of its member operators . This is done for convenience, but you need to be careful that the operator, if there is a function of the same name used in the program from different namespaces.

The namespace is good there, where it is necessary to group something in the area of visibility by name. For example in the program two different functions can be described by sum(). One returns an integer, second real. If the task can not be described as overloaded, it can be screwed into their namespace:

The namespace defines a scope here for various functions with the same name. Outside the namespace of these functions does not exist.

c++, local and global variables, the scope of variables, c ++ beginners, namespace

In general, a namespace can become a point of contention concerning the area of visibility of the theory. In fact it's just a group named, but it has the same effect, as well as a block of statements {…}. Do you want to apply to the operators of this space – be kind to turn first to the name space: integer :: sum() Tut colon :: – an operator extension of area of visibility.

Perhaps the last, we can say – the area of visibility is very revealing in OOP (Object Oriented Programming). When in class programmer describes private property (variable or function method), he asks her area of visibility. For example, in the type code:

properties k and kc They have areas of visibility. The first is available only within the class methods. For it can not be accessed in the main program, it is private (private ). Closed to all, except in the area of visibility of the class.

The second public (public). Its area of visibility extends beyond the class. From the program, which will be called an object of this class is available.

c++, local and global variables, the scope of variables, c ++ beginners, namespace

kc It is declared as a public variable, its area of visibility, unlike the change k , wider. Therefore, the compiler does not against its use outside of class.

What can we draw from all this conclusion? Geeks foaming at the mouth screaming on all portals – “Down with global variables!”. Geeks like to limit the area of visibility, locating and packaging everything into classes or namespaces. Geeks there are geeks. The programmer must not abuse the area of visibility, not to get, rendering, when to refer to a variable you need to write it the way. That is. something like myname::group1::PeremenkiDlaPrepoda::i Well, just a tin.

The use of global variables, along with the local should be wisely – where appropriate write global. Where there is no – localize.

If you have not watched the video on the subject area of visibility in C ++ in the previous lesson – specially for you to place it here:

Newsletter of programming:

Local and global variables. Area of ​​visibility.

c++, local and global variables, the scope of variables, c ++ beginnersFor the understanding of localization variables probably start with an allegory. What “Locality”? This limitation of capacity space. Variable scope – this is the piece of code (function, loop, namespaces), in which the variable is declared (spelled). Outside of this area – the compiler does not see it (it is not available).

So it turns out – Variables such as described within functions, They can not be used abroad. As an example, consider the following code:

Let's look at an example of a closer. So we have a variable i, described is any function in the program. Its scope and actions – the entire program is not limited to. And once she “legitimate” the entire program, in all its functions and operators blocks, prisoners {}, then it is called Global variable.

As we have seen in the example of the function sum(), that something does. It is described in the second variable – k. She already has a specific “registration” – function. Furthermore, this variable can not be used outside the function. That is. if function main() finish is also the conclusion of the k the screen, compiler starts “swear”. It it just simply does not see outside the function sum(). Check out:

Variable k It called local, and its area of ​​visibility defined opening and closing braces function sum(){…}. Then they do not have it running, therefore it can not be used outside this function. Compile:

c++, local and global variables, the scope of variables, c ++ beginners

but, one must also take into account the, that the scope is extended to the indoor units. For example, consider this code:

It manifested the following scope:

  • global – i = 2 hers;
  • Local in the function – variable k;
  • Local relative for loop() – second i.

Despite, that for has its own scope, himself for member function sum(). And it means, and everything in it is, It is subject to the local scope of the function. That is. all variables, function defined in the same way and in the actual body for, which allows the operator to work k += 1 (he is k = k+1 or k ).

More interesting is the case of a variable i, described in for. Despite the name, identical with the global variable as described above, that's another variable.

As soon as their cycle worked, variable i, described in it, loses its power, or in other words – “freed up” from duties. I'm not kidding – just that the memory manager arrives. When a variable is described, Manager reserves under her memory, and when its scope ends – This frees the memory. Memory manager at marks, that this memory location is not owned by anyone, and it is possible to give a recording of other data.

To fix another light primerchik:

It describes the scope block statement, limit {}, That is. first cout displays 2, because the defined block of statements, in which it works cout. And in the same block is defined local variable named and, from it he will value above all.

c++, local and global variables, the scope of variables, c ++ beginners

And already outside {} operator cout displays 0, because there is not the same for him and, that equals 2. Its scope is the same as the other and, which equals 0, and picked up a nested block.

Generally remember – in real life you should never give the same names of variables (except, that is classically used for loop counters. For example i, j, k. If you 10 loops in the code and they are not invested, then for each of them can declare and define the counter with a name i. This is normal). In other cases,, always give unique names to the variables, if you do not want, to you later “recalled” programmers, which will be dealt with in your code.

We also offer to view a video tutorial on the scope. Author video tutorial: Markov Denis

Newsletter of programming:

Built-in functions (inline functions)

built-in features of C ++, инлайн функции, inline functions, Programming for beginnersInline functions very interesting vestige, inherited from the modern world is already far bandit 90. When flourished assembler, Xi compiled very compact and small programs, when processors were weak (compared to the, now put in for example mobile telephones) and code execution time valued its weight in gold. This type of features generally used not only in C, and at the time, he justified himself dashing.

I think, It is not no secret, that old computers required for writing software for heavy computation quite the same serious approach to programming position. Unscrews and had to save on everything, otherwise runtime increases in times. It is now we Rides gigabyte toys are not particularly complaining about the speed. At that time it was extremely critical, and one way to reduce the time, just were inline (integrated) functions. Now I will try to more or less available to tell why.

So, what a normal function? Take for example a simple example – factorial calculation.

Fairly simple factorial (5!) in the for loop, and returns the result of the function. C ++ sees this function as a unit operations, grouped in a single block. Block after the compilation is placed in a memory cell once code, and body functions (in this case cycle) nowhere else in the compiled program does not repeat. Everything is beautiful – get a piece of memory, owned program, processor which jumps if necessary from the point, where is the challenge.

In this statement And this function is enabled, processor simply performs assembler command CALL, which will be transferred to the function address. That is. function call will cost one operator (if roughly speaking). When this, in memory (more precisely in the program stack) It is engaged in place for function parameters, if they are, and be sure to address, where the processor has jumped on the function.

Inline feature saves CPU jump into a cell, at which the function begins. The very meaning of inline It is, that instead of calling the function to substitute her body (function code) in place of, where it is called.

If so describe our factorial:

So instead

we get a reversal function in the set of operators:

as if themselves in the code written at this point.

Accordingly, the type of code:

turn into

Measured philosophically – code number with inline increased function. Instead of a single call line of her body functions, the substituted instead of calling , It gave the whole 6 strings. You will be in a compiled program – the number of operators will increase many times – on many, many operators in the function body, and how much time it entered into the program.

That is. the difference between inline function and normal function – duplication of body function code everywhere, where she is involved. In normal function, its body is in a single copy in the same location within the program.

Where the benefit is you ask? Saves CPU time on the jumping place of call in the body of the function. If the function is a huge and used in several places, then inline It turns out not very profitable. but, if the function (her body) small, with a minimum number of operators, solving the problem, in the old days it was easier to give up the jump and just substitute them in the right place, as the programmer described them there.

Whatever it was, in living conditions and even on modern computers, program, using inline body substitution function instead of calling, no particular benefits. Therefore, use this kind of function is necessary infrequently. IMHO, him a place in the Museum of Fame. Although, to be honest, this approach gives the fruit, who program controllers, processors and other piece of iron. But there is its own peculiarities and its approach, and go into that right now it is not necessary. Use built-in function (inline function) or not – decide for himself programmer. From my own experience, only one – do not make it there, where it is not required for the job.

Newsletter of programming:

Recursion C ++

рекурсия с++, Fibonacci c ++

In C ++ any function except main() can call itself. That is, in the body of the call can be placed the same function. This is called recursion.

When the program executes the code of a recursive function – she will perform it indefinitely, if you do not provide a condition to exit the recursion. This should be remembered, to avoid looping calls. Therefore, in the definition of recursive function must specify the exit condition. For example, You can place it inside the block call if.

In this program function recursionGoDown() will call itself, until it is transferred to a number greater than zero. Every time, function gets the number of, from which is subtracted in the signature unit. As soon as the condition becomes false (the number will be less than zero) – calls to stop and start the output of the recursion.

If we pass in a function number 9, calls will 10. The program as it deepens on 10 levels, performing recursion. To her out of the recursion, We must pass these ten levels back. So the string of code

will run too 10 times, but the value someNumber will change in the opposite order. First, it will conform to, that was passed to the function in the 10 level of recursion, then passed on to the fact that 9 level, etc..

рекурсия с++, Fibonacci c ++

I want to draw attention to an important point. Each recursive call creates a new variable someNumber with the new value. These variables will occupy some space in RAM. If the call 10, as in our example, and it will be stored in the memory 10 with different values ​​of the variables. It is possible to add to the program output to the screen addresses, which stores these values ​​and see this:

Passing in a function number 2: recursionGoDown(2); Levels of recursion is 3.

рекурсия с++, Fibonacci c ++

As seen, each value of a variable someNumber stored in a separate memory segment. During the return to recursion values come from the same addresses but in reverse order.

Almost every task, which can be solved using recursion, can be implemented using iteration loops. You can in fact easy to show on the screen the number of 9 to 0 and by 0 to 9 applying loops. In addition, you should know, that recursion takes more memory and calculation will produce slower, than the iteration.

But, as claimed by experienced programmers and many authors of books, this does not mean, recursion is useless. There are tasks, decide which, using iteration loops, difficult and cumbersome. A recursive solution looks better. For entry-level, until you learn only basics of programming in C ++, you just need to understand, what a recursion is and how it works.

See more videos on the topic of Recursion with 6′ (Author video: Denis Markov).

Newsletter of programming:

Templates C ++ functions

function templates c ++, c ++ templates functions, template c++

A little earlier, addressed the topic of function overloading in C++. You learned about the opportunity to write several functions with the same name, who perform the same tasks. The main difference between them – signature (parameter types and / or number of parameters). When the program starts, the compiler will choose, which of the overloaded functions apply (on the assumption that, that passed to the function)

The same templates allow functions to handle different data types, transmitted as parameters. But it is enough to write one common definition of a function. See how it looks.

function templates c ++, c ++ templates functions, template c++

By defining a function template we used C ++ reserved words: template and typename. template suggests that, that will now define the template. And in angle brackets after typename given a conditional name of the data type. Here, instead of name T, you can assign any (very desirable correct) name.

Next is determined by the function itself. Specify the type of the return value T. Options: the number of type T, and the number of type int. This function finds the number and percentage of the value in the program returns. And the number, and the percentage passed as parameters. For example the first parameter we pass to an integer function (100). During start-up, the compiler will note that currently T this is int and replace the template functions, all these T on int. Thus, the compiler function has the form:

function templates c ++, c ++ templates functions, template c++

We do not see clearly, but everything works great. Whatever the number, we have not passed to this function as the first parameter, the compiler will create an instance of a function template for any call. Here, the first parameter can be any type of data.

As a result, the screen will see the result of this calculation:function templates c ++, c ++ templates functions, template c++

Speaking about the definition of a function template, i want to add, in angle brackets after the keyword template possible to record several conventional names for data types. Why you might need to do this? Consider this example:

It is necessary to write a function, which will take two numbers, determine the maximum of them and return it in the program. Will be given, that function we can pass the number of different types of. The case is, one number is an integer, and the second – material. See what happens:

The first and second parameters are defined function, as type parameters T. With function calls in strings 19-20 no problem, since the transfer parameters are of the same data type. Problems arise in the string 22 compile. And this is understandable. The compiler will get confused. He can not convert type int in double.

шаблоны функций c++, шаблоны функций с++, template c++

To work around this problem, it is necessary to write another template.

Here typename T_1 indicates the type of parameter, that is passed in to the function first. typename T_2 respectively indicates the type of the second parameter. This version of the definition of the function template will alert errors, resulting in the transmission of different types of parameters.

function templates c ++, c ++ templates functions, template c++

It is important to remember,if you are in angle brackets give you a few names for conventional types of function parameters (as in our example), all these type names must be mentioned in the function signature. Otherwise avoid errors when compiling. For example is the definition of a template

function templates c ++, c ++ templates functions, template c++

It leads to the following errors:

шаблоны функций c++, шаблоны функций с++, template c++

The template we defined them conditional types T_1 and T_2, and the signature of the prescribed type only T_1 .

In practice, you can meet the definition of a function template in such a way, where instead of the keyword typename the use of the word class. For example:

function templates c ++, c ++ templates functions, template c++

it is equivalent to the definition of, which we considered

function templates c ++, c ++ templates functions, template c++

Previously, before the C ++ 98 standard, in templates always used the word class. Now better, when there was a keyword typename , better to use it. Because it is more clearly says that, that the names T_1 and T_2 They represent the type.

To summarize. The template function is designed to create a generalized description of the function. Such a function can take parameters of any type. The template allows the compiler to generate code for a specific function such as (or types) data, that was passed into it when you call.

Must see video. About templates with a 14-minute:

Newsletter of programming:

Function overloading in C++

c++ function overloading, function overloading c ++

Perhaps, someone from beginners scares the topic title “Function overloading”? Scares me. It seemed – It is something, what have long to understand. Actually, function overloading is very easy to understand. There is nothing complicated.

Overloaded functions – this function, that have the same name, but differ in the number of accepted parameters or types. Or – both.

To start to define what is the essence of the use of overloaded functions. It consists in the fact, you can give the same name functions. When this, they may be performed in various ways and various types of return values. For example, function should take an array of numbers and return the program to the sum of its elements. But we can pass in an array of function int or type double. In this case we can not provide different functions names. They're essentially performing the same work, just use different data types.

The following program defines three overloaded functions named sumElements(). All of them calculate the amount of array elements. One takes an array type int and its size. The second takes an array type double and its size. The third takes two array type elements int and double and their size.

Definitions of overloaded functions are located in the strings 31 – 61. They create a variable to store the sum of the values ​​of the array elements. In a for loop the amount of accumulated. Next, the resulting value is returned to the program, to place a call to an overloaded function.

Title to all three functions performed by one and the same name – strings 17, 21, 25. Passed to the function when calling an array of type int, and its size, the compiler will automatically detect, which of the three overloaded functions it is necessary to use. Similarly occur during call other functions.

c++ function overloading, function overloading c ++

The most important role in overloaded functions it plays a parameter list. It is also called a signature function. In order to use overloaded functions their signature must be different. Otherwise, the compiler will not be able to determine, what kind of function you want to use in a particular case,. That is, in the signature must be different number of parameters, types, or both, and the second.

How not to do:

c++ function overloading, function overloading c ++

With this announcement, even considering the fact, function that return data with different types of, and what the parameter names are different, the compiler can not determine which of the two functions cause. These signatures are identical in type and number of parameters. Therefore, these functions can not be overloaded.

Watch a short video about the overload:

Newsletter of programming:

Options (arguments) the default function.

c ++ defaults, c ++ default arguments We have already talked about function parameters in a separate article. In this – In short, we will understand, what the default settings function. It is easy to understand. Their use in programming primarily for convenience. For example we need to draw 5 identical rectangles. To do this, we can write a function, that takes the default settings. She draws, let's say, rectangle 10 on 10 characters. And this character is always ‘@’:

Although we do not pass any parameters in the function when calling, we will see five identical rectangles of characters ‘@’ on our screen. Function used those values, that have been assigned default settings when determining.

But that's not all. Even if we have defined the default settings – There is a convenient opportunity to modify their values when calling.

Let's, it is necessary to draw a rectangle 5 characters in width. Other parameters (10 characters in height and the character ‘@’ ) we arrange. Then we pass to the function only one parameter. The remaining options will function from the default.

c ++ defaults, c ++ default arguments

If we need to change only the character and the parameters it is listed last, you will need to write the preceding parameters, even if they are satisfied with us.

c ++ defaults, c ++ default arguments

On the screen see:

c ++ defaults, c ++ default arguments

Another point, which relates to the definition of the default settings in the function header. Defines they have the right to the left. For example, if three of the parameters must be set only one default, It should be defined as an extreme right.

with default parameters ++, arguments default c ++, c++

In the picture the last default setting : char symb = ‘@’. If it is necessary to define two – the same way they would be two extreme right:

If you declare a function prototype – it is necessary to define the default settings it is in the prototype. The definition of functions do not have to do this. Perhaps everything. If something is not clear – ask in the comments.

Newsletter of programming:

Functions in C++

functions in c++, function c ++

Having not such a long way from our first lesson to that, you “reached” to the study of functions in C++. Functions – It is a named piece of code, which is repeated in the program 2 or more times . When we write the function, you must give it a name in the future, чтобы её вызвать в программе (of main() or another function), It is necessary to refer to it by this name.

We have already met functions in previous lessons. This functions for strings (character arrays) strlen(), strcmp(), function for generating random numbers rand(). We used them in programs and, for example, passed to the function strlen() string, and she returns to us the number of characters in this string (integer). This of course was not magically, and the function took our string, handle it and return to us the value, that counted. That is, someone wrote to us this is the function code, which considers the length of the string and we successfully use it in your programs. And this feature is great saves our time, reduces the number of strings of code and facilitates its readability.

Yes – we have these wonderful standard library functions, that we can apply in their programmes, but in most cases, each new assignment is unique and standard features do not always fit. In C ++, the programmer can write your own function independently and to apply it with the same success, as library functions.

Up to a certain time, you can do without features. Instead, to produce the same section of code in the entire program. But if you have to change the code (update or remove something from it), we need to make changes throughout the program. It is better to learn the topic features and actively apply.

Define the function in two ways:

  • to main-functions;
  • after main-functions. In this case it is necessary to main-function to announce its own function prototype.

In this article and the following, we will use the second method, as it is more common. The first method can be used, if one function and its code is very small. While we write simple programs, this happens often. But for the more difficult programs, will write more functions that will not consist of 2-3 strings, and more. Will show you what it looks like a function definition to main():

Using a prototype it will look like this:

The function prototype is placed within a string 4, and its definition is at the bottom of the program in strings 20 – 25. With regard to the implementation of the programme: first prototype compiler reads. This will give him to know about, that somewhere after the main() the definition of this function is located. Next, begin execution of the main function main(). It will be performed, the compiler does not yet meet the function name ourFunctionForPrint(). Then he will find the function definition, which is the value following main(), by name, in the specified prototypes, executes its code, then back to running commands main-functions.

As a result, the screen will see:

functions in c++, function c ++

Let's talk about the definition of functions.

Functions in C ++ may not return any values (as in the example) and may return any value. If the function returns nothing, it is a function of type void.

Function syntax, that does not return a value:

функции c++, функции в с++

The function name should be given to keeping the rules for variable names. Only – it is desirable to contain a verb, because the function performs an action. For example, if it considers the arithmetic mean, you can give a name calculateAverage, if the output is something on screen – showText. The name should speak for itself, it was not necessary to leave unnecessary comments in the code.

Options (or function arguments) – this data, which receives and processes function in the body. If the function does not need anything accept for processing, parentheses are left empty. According to the rules High Integrity C++ Coding Standard it is advisable not to define functions with greatandnumber of parameters (more 6).

Consider a couple of examples of the functions, that accept parameters and does not return values.

It takes one parameter:

In the 10th string of code gets the parameter function – integer 7. With him (with this number) happens then, that described in the definition of the function – strings 16 – 22. Namely – This number is placed in the header of the loop for. Expression i < questionCount would be equivalent to i < 7 . As a result, we will see on the screen 7 question marks.

functions in c++, function c ++

It takes three parameters:

function c ++, functions in c++

Function syntax, that returns a value:

функции в с++, функции c++

These functions differ, that you must specify the type of the value, which returns a function as a result of its work. Itself returns the value in the program is executed by the operator return and that the value of the program will receive at the point, where the function was called . return can return a variable, constant or result of the expression (for example: return variable1 - variable2; ). The body of the function may be several operators return. Then, work function is complete, if the work of some of these operators. For example:

The function definition is located in strings 28 – 34. If the user enters +, work flow if in string 30, and accordingly it will work return d1 + d2; . Then the function code will no longer be processed further. The compiler will return to perform main-functions.

function c ++, functions in c++

You may have noticed, that in the previous code, the parameter names in the prototype and the function definition differ from variable names, which are passed to the function of main. The point following – parameters defining the function prototype and the formal. When we pass the variables as parameters, function will not work with the original variable, and their replicas. These copies are created in the main memory at the time of calling a function. It works with the local copy, and upon completion of the work, copies are destroyed. So the prototype, you can use the exact variable names, but in any case, the function will not work directly with them, and with their counterparts. That is, the variables do not change, it may. When you become familiar with the following lessons pointers and links – learn, how you can change the values ​​of variables passed in the function body.

A little more about the prototype: reading it before main, compiler receives information about, what type of return value is a function (or she does not return a value – has type void) and that, which parameters are transferred into it, how much and in what sequence.

Prototype int calculateSomeDigits(int d1, int d2, char ch); He tells the compiler, that function will return to the scene of her call to an integer and that, a call that it must be passed two integers and one symbol. When calling a function, we have to give her as many parameters as indicated in its title when determining. Transmit parameters must be in the same order, as identified in parentheses following the name of the function. Otherwise errors will occur when you compile a program does not work correctly.

Syntax function prototype:

function prototype in C ++

If several parameters – they must be separated by a comma. The easiest way to declare the prototype – This is a copy from the first string of the function definition (header) and after the closing parenthesis to add a semicolon.

functions in c++, function c ++, function prototype

Variable names prototype parameters can be omitted. The following is equivalent to prototype, that the above.

functions in c++, function c ++, function prototype

In my opinion, it is better to declare the function prototypes, indicating the names of the parameters. Especially if several options and they have the same type. For readability and understanding of the program it would be better.

To fix it, what does this article, need to practise. See the article with tasks for functions in C++ . In it you will find information on how to, how to pass arrays to functions as parameters. Council – do not just read, and write code! Preferably on their own.

Related Videos:

Look for updates on our website and share links to articles with your friends!

Newsletter of programming: