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:

Functions in C++
5 (100%) 1 vote

24 thoughts on “Functions in C++

  1. Even in the very first lessons you have written, that it is necessary to write at the end of each program return = 0 and added, that in later lessons will explain what to do and what is generally somewhere there return zero. I think, that would have time to fulfill the promise. Please explain why you need a refund and why there may not only be zero. Thanks in advance.

    1. ))) According to the latest standards of C ++, already can not write return 0; The program itself and returns whether we prescribe or not. It means, she (program) fulfilled and closed. But all sorts of other values ​​can be returned to, to catch errors in the work program. For example to program a function of some condition, and if it is not executed – return value of the function -1 (or any other), and if the return is executed 1. Further, the condition register, that if the function returns -1 – The error occurred. returned 1 – You can continue to work (function worked fine).
      You can read our lesson on exceptions in C ++: http://purecodecpp.com/archives/2044

    2. A return at the end of the main functions of the program main(), I will add, returns the result of execution the entire program the operating system: 0 – Good luck, non-zero value – something in the program was not.

      1. The script should respond to the changing colors on the screen, but in a string 11 where the first brace autoit writes that it is not possible to parse a string. Help please:

        var x0 = 0, y0 = 0, x1 = 100, y1 = 100; // screen area of 0:0 to 100:100

        var = crc0 ait.pixelChecksum(x0, y0, x1, y1);

        while(true)
        {
        WSH.sleep(500); // checked every 0.5 sec
        var crc = ait.pixelChecksum(x0, y0, x1, y1);
        if(crc!=crc0)
        {
        crc0 = crc;
        sapi.speak(“Alarm! Picture changed.”) // shouts a human voice )
        }
        }

  2. Actually, everything related to the specifics of the display on the screen, to C ++ does not have any bearing on, and on 100% It is defined as).what are you operating system … try, and b).in which graphical tool, library, tool-се.

    And according to these embodiments, and) and b) different answers and tips can be million.

  3. and) seven, b) I can not understand. Through the program autoit must run this script. Help. Maybe there is another program, that performs the same function, give me a link. Maybe there is a program, which responds to a particular sound?Also give the link if you know. help me please.

    1. 1. I do not know what's in Windows 7 (and I did not really want to know)
      2. Your question does not apply any sideways to programming in C ++ … and even programming in general – it is a question about the specific programs and their use.
      4. if you have specifically set out the. questions (What do you want?), and even without regard to specific Windows OS 7 (as generally solve such problems?) you can ask:
      https://toster.ru/my/feed – here
      http://rus-linux.net/forum/index.php – or here

  4. thanks for the info! And how to make a library of functions? Thank you in advance( Sorry for mistakes, if there is!) )

    1. Do you clearly understand what you want, when you say “library”?
      1. You can create a separately compiled object file, containing some of your functions, and this file will be collected together with your application.
      2. You can create static library, which must be collected along with your application.
      3. You can create dynamic library, shared, DLL, which is to be loaded (system) during the execution of your application.

  5. As can be assigned to the result variable in function of the basic function?
    For example: one function at double call back two results.
    How can they possibly compare?
    As these results are assigned to the variables in the main function.?

    1. Like this:

      Or even just like that:

Leave a Reply

Your email address will not be published. Required fields are marked *