Creating a function in C. Functions in the C programming language

It's time to learn about the features. Do you already know how to use main functions, is another example of a function. In general, functions are separate, independent blocks of code that execute a set of predefined commands. In the C programming language, you can use both the built-in functions of various libraries and functions that you have created yourself, that is, your own functions.

Functions that we will create ourselves usually require a prototype declaration. A prototype gives basic information about a function's structure: it tells the compiler what value the function will return, how the function will be called, and what arguments the function can be passed. When I say that a function returns a value, I mean that the function will return some value at the end of its work, which can be put into a variable. For example, a variable can be initialized with a value that a function will return:

#include // connection of the header with the function rand rand() int randomNumber = rand(); // standard random number generation function

The mistake is that many novice programmers think that the value in the randomNumber variable will randomly change every time, this is not so. It will be initialized random value once, when the function is called, but not every time the program is started.

Consider the general format for a function prototype:

ReturnedDataType functionName (dataType par1, ..., dataType parN);

where, returnedDataType is the data type returned by the function, the value;
functionName — function name
dataType - the data type of the function parameter, this is the same data type as when declaring a variable
par1 ... parN are function parameters.

A function may have more than one parameter, or none at all, in which case the parentheses are empty. Functions that do not return a value have a return data type of void . Let's look at the function prototype:

int mult (int x, int y);

This prototype tells the compiler that the function takes two arguments as integers, and that the function will return an integer value when it completes. Be sure to add a semicolon at the end of the prototype. Without this symbol, the compiler will most likely think that you are trying to write the actual function definitions.

When a programmer actually defines a function, he will start from the prototype, but the semicolon is no longer necessary. Immediately after the prototype, there is a block with curly braces and with the code that the function will execute. For example, how do you usually write code inside the main function. Any of the arguments passed to the function can be used as if they were declared as ordinary variables. And finally, the function definition ends with a closing curly brace, no semicolons.

Let's look at an example of declaring and using a function in the C programming language:

#include int multiplication(int num1, int num2); //function prototype int main() ( int num1; int num2; printf("Enter two numbers to multiply: "); scanf("%d", &num1); scanf("%d", &num2); printf(" Result of multiplication %d\n", multiplication(num1, num2)); // function call getchar(); return 0; ) int multiplication(int num1, int num2) // function definition ( return num1 * num2; )

This program starts by including a single header file, on line 1. The next line is the prototype of the multiplication function. Note that there is a semicolon at the end of the prototype declaration! The main function returns an integer, on line 16. To comply with the standard, the main function must always return some value. You shouldn't have any problems understanding the input and output of values ​​in functions if you've read the previous lessons carefully.

Notice how the multiplication() function actually takes a value. What is really happening? And in fact, it works like this: the multiplication function takes two integer values, multiplies them and returns the product. The result of this program will be exactly the same as if we did this:

Printf("Result of multiplication %d\n", num1 * num2);

The multiplication() function is actually defined below the main function. And since the prototype of this function is declared above main function, then the compiler will not throw an error when calling the multiplication() function inside main(). As long as the prototype is present, the function can be used even if there is no actual definition of it. However, a function call cannot be made before the function is defined.

Function prototype definitions are only necessary if the actual definition of the function itself will come after the main function. If the function is defined before the main function, then the prototype is not needed.

The return keyword is used to make a function return a value. Note that you can quite successfully declare functions that do not return any values. If a function returns a value of type void , then the function does not actually have a return value. In other words, for a function that returns a value of type void , the statement return; is legal, but it is usually redundant. (Although it can be used to exit a function in an emergency.)

The most important thing is to understand why do we need a function? Functions have many uses. For example, a program has a block of code that needs to be executed in different places in the program about forty times. That is, you declared a function once and already call it where necessary, while the code is not duplicated, which will save a lot of space, which in turn will make the program more readable. Also, having only one copy of the code makes it easier to make changes.

Another reason to use functions is to separate all code into separate logical parts. In this way, complex tasks are broken down into simpler ones, it helps a lot when maintaining the code, the structure of such a program will be much easier to understand.

P.S.: if you need a good server, then you can rent servers in Moscow. You can also use other services provided on the site it-express.ru: deployment of fault-tolerant servers, data storage systems, etc.

Until now, we have written programs as a single, functionally indivisible code. The program algorithm was in the main function, and there were no other functions in the program. We wrote small programs, so there was no need to declare our functions. For writing big programs, experience shows that it is better to use functions. The program will consist of separate code fragments, a separate code fragment is a function. Separate, because the work of a single function does not depend on the work of any other. That is, the algorithm in each function is functionally sufficient and independent of other program algorithms. Once a function has been written, it can be easily transferred to other programs. A function (in programming) is a piece of code or an algorithm implemented in some programming language in order to perform a certain sequence of operations. So, functions allow you to make the program modular, that is, to divide the program into several small subroutines (functions), which together perform the task. Another huge plus of functions is that they can be reused many times. This feature allows you to reuse once written code, which in turn greatly reduces the amount of program code!

In addition to the fact that C ++ provides for the declaration of its functions, you can also use the functions defined in the standard header files of the C ++ programming language. To use the function defined in the header file, you need to include it. For example, to use a function that raises some number to a power, you need to include the header file and run the pow() function in the body of the program. Let's develop a program in which we will run the pow() function.

// inc_func.cpp: defines the entry point for the console application. #include "stdafx.h" //action 1 - include the header file

// code Code::Blocks

// Dev-C++ code

// inc_func.cpp: defines the entry point for the console application. //action 1 - include the header file which contains prototypes of basic mathematical functions #include int main(int argc, char* argv) ( float power = pow(3.14,2); //action 2 - start the exponentiation function return 0; )

Header files are included as shown in line 5, i.e. the preprocessor directive #include is declared, after which, inside the characters<>the name of the header file is written. When the header file is included, you can use the function, which is done in line 9.pow() function raises a number 3.14 squared and assigns the result to the variable power , where
pow is the name of the function;
the numbers 3.14 and 2 are the arguments of the function;

Parentheses are always placed after the function name, inside which arguments are passed to the function, and if there are several arguments, then they are separated from each other by commas. Arguments are needed in order for the function to pass information. For example, to square the number 3.14 using the pow() function, you need to somehow tell this function what number, and to what power to raise it. This is exactly what function arguments were invented for, but there are functions in which arguments are not passed, such functions are called with empty parentheses. So, in order to use a function from a standard C++ header file, you need to do two things:

  1. Connect the required header file;
  2. Run the required function.

In addition to calling functions from standard header files, the C++ programming language provides the ability to create your own functions. There are two types of functions in the C++ programming language:

  1. Functions that do not return values
  2. Functions that return a value

Functions that do not return values, after completing their work, do not give any answer to the program. Consider the structure of the declaration of such functions.

// declaration structure of non-returning functions void /*function name*/(/*function parameters*/) // function header ( // function body )

Line 2 starts with the reserved word void, which is a data type that cannot store any data. The void data type means that given function does not return any values. void is not used in any other way and is only needed so that the compiler can determine the type of the function. The reserved word void is followed by the name of the function. Immediately after the function name, two parentheses are placed, opening and closing. If you need to transfer some data to the function, then the function parameters are declared inside the round brackets, they are separated from each other by commas. Line 2 is called the function header. After the function header, two curly brackets are written, inside of which there is an algorithm called the function body. Let's develop a program in which we declare a function for finding the factorial, and the function should not return a value.

<= numb; i++) // цикл вычисления значения n! rezult *= i; // накапливаем произведение в переменной rezult cout << numb << "! = " << rezult << endl; // печать значения n! } int main(int argc, char* argv) { int digit; // переменная для хранения значения n! cout << "Enter number: "; cin >>digit; faktorial(digit);// run the function for finding the factorial system("pause"); return 0; )

// code Code::Blocks

// Dev-C++ code

using namespace std; // declaration of a function for finding n! void faktorial(int numb)// function header ( int rezult = 1; // initialize rezult variable with value 1 for (int i = 1; i<= numb; i++) // цикл вычисления значения n! rezult *= i; // накапливаем произведение в переменной rezult cout << numb << "! = " << rezult << endl; // печать значения n! } int main(int argc, char* argv) { int digit; // переменная для хранения значения n! cout << "Enter number: "; cin >>digit; faktorial(digit);// run the function for finding the factorial return 0; )

After all the necessary header files have been included, you can declare the function for finding the factorial. By declaring a function, you mean choosing a function name, defining function parameters, and writing an algorithm that is the body of the function. After completing these steps, the function can be used in the program. Since a function must not return a value, the return type must be void . The function name is faktorial , inside the parentheses the numb variable of type int is declared. This variable is a parameter to the faktorial() function. Thus, all ads in line 8 collectively make up the header of the function. Lines 9 - 14 make up the body of the faktorial() function. Inside the body, on line 10, the rezult variable is declared, which will store the result of finding n! After that, in lines 11-12 The for loop operator is declared to find the factorial. AT line 13 the cout operator is declared, with the help of which the factorial value will be printed on the screen. Now that the function is declared, we can use it. AT line 21 the faktorial(digit) function is launched, the argument is passed inside the parentheses to the function, i.e. the value contained in the digit variable. The result of the program (see Figure 1).

Figure 1 - Functions in C++

So, after running the program, the number 5 was entered, and the program calculated that the value 120 is 5!.

Functions that return a value, upon completion of their work, return a certain result. Such functions can return a value of any data type. The structure of functions that return a value will be slightly different from the structure of the functions discussed earlier.

// declaration structure of functions returning values ​​/*return data type*/ /*function name*/(/*function parameters*/) // function header ( // function body return /*return value*/; )

The structure of the function declaration has remained almost unchanged, with the exception of two lines. In the function header, you first need to define the return data type, it can be an int data type if you want to return an integer, or a float data type for floating point numbers. In general, any other data type, it all depends on what the function should return. Since a function must return a value, a special mechanism must be provided for this, as in line 5. With the help of the reserved word return, you can return a value when the function ends. All that is needed is to specify a variable containing the desired value, or some value, after the return statement. The data type of the return value in line 5 must match the data type in line 2. Let's rewrite the factorial program so that the faktorial() function returns the value of the factorial.

// struct_func.cpp: defines the entry point for the console application. #include "stdafx.h" #include <= numb; i++) // цикл вычисления значения n! rezult *= i; // накапливаем произведение в переменной rezult return rezult; // передаём значение факториала в главную функцию } int main(int argc, char* argv) { int digit; // переменная для хранения значения n! cout << "Enter number: "; cin >>digit; cout<< digit << "! = " << faktorial(digit) << endl;// запуск функции нахождения факториала system("pause"); return 0; }

// code Code::Blocks

// Dev-C++ code

// struct_func.cpp: defines the entry point for the console application. #include using namespace std; // declaration of a function for finding n! int faktorial(int numb)// function header ( int rezult = 1; // initialize rezult variable with value 1 for (int i = 1; i<= numb; i++) // цикл вычисления значения n! rezult *= i; // накапливаем произведение в переменной rezult return rezult; // передаём значение факториала в главную функцию } int main(int argc, char* argv) { int digit; // переменная для хранения значения n! cout << "Enter number: "; cin >>digit; cout<< digit << "! = " << faktorial(digit) << endl;// запуск функции нахождения факториала return 0; }

The faktorial() function now has a return data type of int , because n! is an integer. line 13 declared a return statement that returns the value contained in the variable rezult . AT line 21 we execute the function faktorial() , the return value of which is sent to the output stream using the cout operator. One could write it like this: int fakt = faktorial(digit); - type variable int we assign the return value of the faktorial() function, after which the variable fakt will store the value n! . The result of the program has not changed (see Figure 2).

Enter number: 5 5! = 120 Press any key to continue. . .

Figure 2 - Functions in C++

We considered two types of functions, and the declaration of functions was performed in the program area, after including the header files, but before the start of the main() function. There are several ways to declare functions (see Figure 3).

Figure 3 - Functions in C++

On the figure 3 4 ways of declaring functions in the C++ programming language are shown. Let's consider function declaration structures in one file, with the main function. Functions can be declared in two areas, before the start of the main() function, after the main() function. So far, we have declared functions in one file, before the main() function - this is the easiest way.

// struct_func.cpp: defines the entry point for the console application. #include "stdafx.h" /* area 1 - function declaration before main() start place for function declaration functions declared in this area do not need prototypes */ int main(int argc, char* argv) ( return 0; )

If functions are declared in area 1, before the main function, then prototypes for these functions are not needed. It is good programming style to declare functions after main() . Consider the structure of such a function declaration.

// struct_func.cpp: defines the entry point for the console application. #include "stdafx.h" // place to declare function prototypes int main(int argc, char* argv) ( return 0; ) /* area 2 - function declaration after main() place to declare functions */

// code Code::Blocks

// Dev-C++ code

// struct_func.cpp: defines the entry point for the console application. // place to declare function prototypes int main(int argc, char* argv) ( return 0; ) /* area 2 - function declaration after main() place to declare functions */

The function declaration area has moved to the very end of the program, after main() . As for the method of declaring functions, it has not changed. But since the functions are declared after main() , it will not work to use them, because the order of declarations has changed and the main() function simply will not see the functions declared after. So, in order for these functions to be seen in main(), there is the concept of a prototype. A function prototype is a function header that is declared before the main() function. And if you declare a function prototype, then the function can be seen in main() .

// prototype declaration syntax /*function return data type*/ /*function name*/(/*function parameters*/);

The structure of a prototype declaration is very similar to that of a function declaration. Let's develop a program that determines whether the entered five-digit number is a palindrome. A palindrome is a number or text that reads the same on the left as it does on the right: 93939; 49094; 11311.

// palindrom_func.cpp: defines the entry point for the console application. #include "stdafx.h" #include << "Enter 5zn-e chislo: "; // введите пятизначное число int in_number, out_number; // переменные для хранения введённого пятизначного числа cin >> << "Number " << out_number << " - palendrom" << endl; else cout<<"This is not palendrom"<

// code Code::Blocks

// Dev-C++ code

// palindrom_func.cpp: defines the entry point for the console application. #include using namespace std; bool palindrom5(int); // prototype of the function for finding the palindrome of five-digit numbers int main(int argc, char* argv) ( cout<< "Enter 5zn-e chislo: "; // введите пятизначное число int in_number, out_number; // переменные для хранения введённого пятизначного числа cin >> in_number; out_number = in_number; // store the entered number in the out_number variable if (palindrom5(in_number)) // if the function returns true, then the condition is true, otherwise the function returns false - false cout<< "Number " << out_number << " - palendrom" << endl; else cout<<"This is not palendrom"<

AT line 7 the prototype of the function for finding the palindrome of five-digit numbers is declared. Please note that the prototype must completely match the function header, but there are still some differences. For example, it is not necessary to enumerate the parameter names in the prototype, it is enough to declare their data types. A semicolon must always be placed at the end of a prototype declaration. Otherwise, the declaration of the prototype is the same as the declaration of the header of a single function. The prototype must be declared for each function separately. The out_number variable is used to temporarily store the entered number. AT line 16 in the condition of the if select statement, the palindrom5() function is executed. Its argument is the variable in_number . the function will return a value of type bool , and if the function returns true , then the condition will be true, otherwise it will be false. It would be possible to first assign the value returned by the function to some variable, and then substitute this variable into the condition of the if selection statement, but this would increase the program code by one line. AT lines 23 - 40 the palindrom5() function is declared, with one parameter, through which a five-digit number is passed to the function. The variables balance1 , balance2 , balance4 , balance5 are declared in line 25, and are needed to store the digits of a five-digit number: the first, second, fourth, fifth (numbering is from right to left). In lines 26, 29, 32, 35, the same operation is performed - the remainder of the division. The remainder operation cuts off one digit from right to left and stores them in the variables balance1 , balance2 , balance4 , balance5 respectively. Moreover, the operation remainder of division alternates with the operation of ordinary division. The division operation is performed in lines 27, 30 , 33 , and decrements the entered five-digit number by one step at a time. AT line 30 the division operation reduces the entered number by two digits at once, because the number is five-digit and the middle digit does not interest us, it can be anything. AT lines 36 - 39 the if selection operator is declared, which compares the digits of a five-digit number, and if they are appropriately equal, then the function will return true , otherwise false . The result of the program (see Figure 4).

Enter 5zn-e chislo: 12321 Number 12321 - palendrom Press any key to continue. . .

Figure 4 - Functions in C++

So far, we've declared functions in the same file as the main program, which is where the main() function resides. In C++, it is possible to place function declarations in a separate file, then it will be necessary to include a file with functions, as is the case with including standard header files. There are two ways:

  1. creation of a *.cpp type file in which functions are declared;
  2. creation of files like *.cpp and *.h.

Good programming style is the second way. Thus, if you declare functions in another file, then do it according to method two. Let's rewrite the palindrome finder so that the declaration of the palindrom5() function is in a separate *.cpp file. The *.h file is needed to hide the implementation of functions, i.e. the *.h file will contain function prototypes. Using the MVS solution explorer, we create a *.h file and name it palendrom .

// file code palendrom.h #ifndef palendrom #define palendrom bool palindrom5(int); // prototype of the function for finding the palindrome of five-digit numbers #endif

Directives in lines 2,3,5 must always be declared in files with function prototypes, and function prototypes are always declared in *.h type files. After the directives written in lines 2,3, but function prototypes are declared before the #endif directive. Line 4 declares the prototype of the palindrom5() function. The declaration of this function is in the palendrom.cpp file, which was also previously created using the MVS Solution Explorer.

// contents of the palendrom.cpp file #include "stdafx.h" #include "palendrom.h" bool palindrom5(int number) // function for finding a palindrome of five-digit numbers ( int balance1, balance2, balance4, balance5; // variables storing intermediate results balance1 = number % 10; // balance1 variable assigned the first remainder number = number / 10; // decrement the entered number by one digit balance2 = number % 10; // balance2 variable assigned the second remainder number = number / 100; // decrement the entered number number by two digits balance4 = number % 10; // balance4 variable was assigned the fourth remainder number = number / 10; // decrement the entered number by one digit balance5 = number % 10; // balance5 variable was assigned the fifth remainder if ((balance1 == balance5) && (balance2 == balance4)) return true; // function returns true else return false; // function returns false )

// code Code::Blocks

// Dev-C++ code

// contents of palendrom.cpp file #include "palendrom.h" bool palindrom5(int number) // function to find palindrome of five-digit numbers ( int balance1, balance2, balance4, balance5; // variables storing intermediate results balance1 = number % 10; / / balance1 variable is assigned the first remainder number = number / 10; // decrement the entered number by one digit balance2 = number % 10; // balance2 variable is assigned the second remainder number = number / 100; // decrement the entered number by two digits balance4 = number % 10; // balance4 variable is assigned the fourth remainder number = number / 10; // decrement the entered number by one digit balance5 = number % 10; // balance5 variable is assigned the fifth remainder if ((balance1 == balance5) && (balance2 == balance4)) return true; // function returns true else return false; // function returns false )

The palendrom.cpp file contains the declaration of the palindrom5() function. Since the palendrom.cpp file is an executable file (*.cpp - executable files), it is necessary to include the "stdafx.h" container in it, as in line 2. To link the file where the palindrom5() function is declared and the file with its prototype, we will connect the header file (the file with the prototype), this is done in line 3. Please note that when connecting the file we created, double quotes are used, and not greater than or less than signs. All that's left is to run the palindrom5() function in the main executable func_palendrom.cpp .

// func_palendrom.cpp: defines the entry point for the console application. #include "stdafx.h" #include << "Enter 5zn-e chislo: "; // введите пятизначное число int in_number, out_number; // переменные для хранения введённого пятизначного числа cin >> in_number; out_number = in_number; // store the entered number in the out_number variable if (palindrom5(in_number)) // if the function returns true, then the condition is true, otherwise the function returns false - false cout<< "Number " << out_number << " - palendrom" << endl; else cout<<"This is not palendrom"<

// code Code::Blocks

// Dev-C++ code

// func_palendrom.cpp: defines the entry point for the console application. #include // include header file, with palindrom5() function prototype #include "palendrom.h" using namespace std; int main(int argc, char* argv) ( cout<< "Enter 5zn-e chislo: "; // введите пятизначное число int in_number, out_number; // переменные для хранения введённого пятизначного числа cin >> in_number; out_number = in_number; // store the entered number in the out_number variable if (palindrom5(in_number)) // if the function returns true, then the condition is true, otherwise the function returns false - false cout<< "Number " << out_number << " - palendrom" << endl; else cout<<"This is not palendrom"<

AT line 6 we have included a file with the prototype of the palindrom5() function, after which we can use this function. So, we split the program into three files:

  • project file: func_palendrom.cpp
  • header file palendrom.h
  • palendrom.cpp executable file

The project file is associated with the header file, and the header file is associated with the executable file, in this case the project file will see the palindrom5() function and be able to run it.

A function is a group of statements that has a name. In all previous lessons, the code of our programs was located in one function - main. Functions allow you to break a program into small parts, each of which performs some small task. Have a look at the full naval battle code (section - Listings). It has over 500 lines of code. Without functions, it would be rather problematic to write this program. It uses 11 functions, the longest of which is 50 lines of code.

Two components are required for a function: the definition and the calls.

Function definition

The function definition must be in the global scope, before the start of the main function. Consider an example of a simple definition:

c++ code

A function definition consists of a header and a body. The function header includes:
return type

Almost all functions must return values. The type of this value is specified in the header before the function name. Here are some examples of function headers:

int simple_function()
float simple_function()
char simple_function()

In the first case, the function must return an integer (int), in the second - a real number (float), and in the third case - a character (char).

Return values ​​are used to pass data from the function to the calling environment. The calling environment is where the function is called from, more on that below.
Function identifier or name

The identifier (name) of the function is set in the same way as any other identifier. In this example, we have created a function with the identifier simple_function (simple - simple).
List of arguments or options

The list of function arguments is written in parentheses after the function name. In this example, the argument list is empty.

The list of arguments is separated by commas. Each element of the list consists of a type and an identifier. Consider an example of a function header with a list of two arguments:

int simple(int a, float b)

In parentheses, we have written two arguments: a and b. The argument a is of type int and the argument b is of type float.

Arguments are used when the function needs to pass some data from the calling environment.
Function body

The body of the function is located immediately below the heading and enclosed in curly braces. A function body can contain any number of operators. But the return statement must be present. The return statement returns a value:

c++ code int simple_function () ( return 0; )

Here, simple_function will always return 0. Admittedly, this function is useless. Let's write a function that takes two values ​​from the calling environment, adds them up, and returns the result to the calling environment. Let's call this function sum (sum):

c++ code int sum (int a, int b) ( int c; c = a + b; return c; )

Two arguments are passed to the function: a and b of type int. In the body of the function, they are used as ordinary variables (they are ordinary variables). Let's agree: outside the function, we will call the variables that are passed into it arguments, and the same variables in the function body - parameters.

The variable c is defined in the body of the function. And then, in this variable, we put the value of the sum of the two parameters.

The last line returns the value of the variable c to the external environment.

After the return keyword, you must specify the value that will be returned. You can return both simple values ​​and variables and even expressions. For example:

return 32;
return a;
return b;
return a+b;

In the latter case, the result of the sum of the variables a and b will be returned to the calling environment.

Please note that the return statement not only returns a value, but also serves as an exit from the function, after it no statement will be executed:

return a;
c = a+b; // this statement will not be executed

Because of this, using return is convenient to create conditions for exiting functions:

c++ code if (a > 0) ( return 0; ) else if (a< 0) { return 1 }

Here, a number will be returned from the function depending on the value of the variable a: if a is greater than zero, then 0 will be returned, otherwise - 1.
Function call

Once a function definition has been created, it can be called.

c++ code int sum (int a, int b) ( int c; c = a + b; return c; ) int main() ( int s; s = sum(2,2); // call cout function<< s; return 0; }

As a result of the program execution, the following will be displayed on the screen: 4.

A function call consists of a function identifier and a list of arguments in parentheses. Here are some calls to the sum function:

int x = 5;
int y = 4;
intz;

sum(0,1); // one
sum(x,2); // 7
sum(x,y); // 9
z = sum(x,y); // z = 9

calling environment

The place where the function is called from is called the calling environment. The calling environment of the sum function is the main function, and the calling environment of the main function is the debugger or the operating system.

A function can communicate with the calling environment thanks to the argument list and return value: the calling environment passes data to the function using arguments, and the function passes data to the calling environment using the return value.

The type of the value passed to the function must match the type specified in the argument list. For example, you can't write like this:

c++ code int simple (int a) ( return 1; ) int main () ( int b; b = simple(0.5); return 0; )

In the list of arguments, we specified the type int, and the real value 0.5 is passed to the function. You can't do that.

Let's consider a more useful example: let's write a function for character movement:

c++ code intx; // global variable int move_x (int dx) ( x = x + dx; return x; ) int main () ( int ch; char act; while (1) ( act = _getch(); ch = static_cast(act); if (ch == 75) // left arrow was pressed move_x(-1); else if (ch == 77) // right arrow was pressed move_x(1); ) // end while return 0; ) // end main

Please note that there are no parentheses for the if and else if body. Branch brackets can be omitted if there is only one statement in the body of the branch.

The move_x function moves the character one unit left or right depending on the key the user pressed.

Let's create one more function, and at the same time remove part of the code from main:

c++ code intx; // global variable int move_x (int dx) ( x = x + dx; return x; ) void move (int ch) ( if (ch == 75) // the left arrow was pressed move_x(-1); else if ( ch == 77) // right arrow was pressed move_x(1); ) int main () ( int ch; char act; while (1) ( act = _getch(); ch = static_cast(act); move(ch) ; // call function move ) // end while return 0; ) // end main

Note that in the move function, the return type is replaced by void, and there is no return statement in the move body.

Function declarations (prototypes)

In the last example, the definition of the move_x function must be placed above the definition of move (and the definitions of move_x and move must be placed before main), since move_x is called in the move function.

Typically, definitions of all user-defined functions are located after the definition of main. In this case, function declarations (prototypes) are used. Let's make changes to the previous program:

c++ code intx; // global variable void move(int); // prototype (declaration) of the move function int move_x(int); // function prototype move_x int main () ( int ch; char act; while (1) ( act = _getch(); ch = static_cast(act); move(ch); // call move ) return 0; ) void move (int ch) ( if (ch == 75) // the left arrow was pressed move_x(-1); else if (ch == 77) // the right arrow was pressed move_x(1); ) int move_x (int dx) ( x = x + dx; return x; )

The function prototype is the same as the definition header, but you can omit the variable names in the argument list in the prototype. The following declarations are equivalent:

int move_x(int ​​dx);
int move_x(int);

Function declarations are located at the beginning of the file. The function prototype tells the compiler that the given function can be called, and its definition will be later (or located in another file).

The function declaration can be placed anywhere in the program (outside the program function definitions or in any definition), as long as it appears before the first function call. If you do not use declarations, then before the first function call there must be a definition, which can also be located anywhere in the program.
return void
In place of the return type, in the definition (and in the declaration) of the move function, there is the keyword void (void - empty, empty). This means that the function does not return any value. Therefore, no return statement is required either, since the function has nothing to return to the calling environment.

In the C language, all programs are treated as functions. Usually programs in this language consist of a large number of small functions. For each of the functions used, a description and definition of the function is provided (The description of the function provides information about the type of the function and the order of the parameters. When defining a function, specific statements are indicated that must be executed). Functions must be of the same type as the values ​​they return as results. By default, functions are assumed to be of type int. If the function has a different type, it must be specified both in the calling program and in the function definition itself.

Consider the description of functions: two different styles of description of functions (classic and modern style) can be used. In the first case, the function declaration format is as follows:

type function_name();

This specification describes the name of the function and the return type.

The modern style is used in the constructions of ANSI Extended C. When describing functions in this version of C, special features of the language are used, known as "function prototype". A function description using its prototype contains additional information about its parameters:

type function_name (par_inf1, par_inf2, ...);

where parameter par_infi is information about the name and type of formal parameters.

Function definition. Just like in the description of a function, two styles can be used when defining functions - classic and modern. The classic format for defining functions is as follows:

type function_name (parameter names)

definition of parameters;

local descriptions;

operators;

The modern-style declaration format provides for the definition of function parameters in parentheses following the function name:

type function_name (par_inf, par_inf, ...)

where parameter definition par_inf – contains information about the passed parameter: type and identifier.

It should be noted that a number of declarations (constants, data types, variables) contained within a function (with the exception of the main function main0) are defined only within this function. Therefore, the C language does not support function nesting, i.e. one function cannot be declared inside another function.

Functions can be placed in a program in any order and are considered global to the entire program, including built-in functions that are declared before they are used.

The function is called by the name of the function, the actual arguments are indicated in brackets.

The result of the function execution is returned using the return statement. General form:

return(expression);

The statement ends the execution of the function and passes control to the next statement in the calling function. This occurs even if the return statement is not the last statement in the function body.

You can use the return statement in the form:

Its use causes the function in which it is contained to complete its execution; control (passed) is returned to the calling function. Since this statement does not have a parenthesized expression, no value is passed to the function.

( floaty,x,mult(); /* description in calling program */

floatmult(v,k) /* description in function definition */

for (res=0.0; k>0; k--)

return(res); ) /* returns a value of type float */

Only one value can be passed to the calling program with the return statement. If you need to pass two values, you need to use pointers.

A function definition specifies a name, formal parameters, and a function body. It may also specify the return type and storage class of the function. The function definition syntax is as follows:

[<спецификация КП>][<спецификация типа>]<описатель>([<список параметров>]) [<объявление параметров>] <тело функции>

Memory class specification<спец. КП>specifies the storage class of the function.

<спец. типа>together with the descriptor defines the type of the returned value and the name of the function.<Список параметров>is a list (possibly empty) of formal parameter names whose values ​​are passed to the function when called.<Объявления параметров>define identifiers and types of formal parameters.<Тело функции>- a compound statement containing declarations of local variables and operators.

Modern design:

[<спецификация КП>][<спецификация типа>]<описатель>([<список объявлений параметров>])<тело функции>

Function declaration: classic form:

[<спецификация КП>][<спецификация типа>]<описатель>([<список типов аргументов>]);

A function declaration specifies the name of the function, the return type, and possibly the types of its arguments and their number.

Modern description style (declaring prototypes). In the list of argument types, the prototype may also contain the identifiers of these arguments.

float f1(float a, float b)

c=(2*pow(a,3)+sin a)/pow(a+b,4);

( float x,y,s=0;

printf("\n Enter x, y");

scanf("%f %f", &x, &y);

s=f1(5.6, y)+f1(2*x-1, x*y);

printf(“\n s=%6.2f ”,s);

address operations. C supports two special address operations: the find address operator (&) and the access address operator (*). The & operator returns the address of the given variable. If sum is a variable of type int, then &sum is the address of that variable.

Pointers. A pointer is a variable that contains the address of some data. Generally speaking, a pointer is some symbolic representation of an address. &sum in this case means "pointer to the variable sum". The actual address is a number, and the symbolic representation of the address &sum is a pointer constant. T.arr. the address of the memory cell assigned to the sum variable does not change during the execution of the program.

The C language also has pointer variables. The value of a pointer variable is the address of some value. Let the pointer be denoted by the identifier ptr, then the following statement assigns the address of sum to the variable ptr:ptr=&sum. In this case, ptr is said to "point to" sum. So, ptr is a variable, &sum is a constant. The ptr variable can point to some other object:

The value of ptr is the address of the variable max. Let's consider the operation of access to the address (*) or the operation of indirect addressing. Let's assume that the ptr variable contains a reference to the max variable. Then, to access the value of this variable, you can use the access to address (*) operation. To determine the value pointed to by ptr, we write the following statement:

Res=*ptr; (The last two statements taken together are equivalent to the following: Res=max;)

Using the operation of obtaining an address and indirect addressing turns out to be far from a direct path to the result, hence the appearance of the word "indirect" in the name of the operation.).

Operation (*) - when this sign is followed by a pointer to a variable, the result of the operation is the value placed in the cell with the specified address.

Description of pointers. When describing variables of the "pointer" type, it is necessary to indicate what type of variable the given pointer refers to. Because variables of different types occupy a different number of cells, while some operations involving pointers require you to know the amount of memory allocated. Examples of the correct description of pointers:

Using pointers to communicate between functions. Consider an example of using pointers to establish links between functions. In this example, pointers are used to exchange variable values.

( int x=5, y=10;

printf("x=%d y=%d\n", x, y);

change(&x, &y); /*pass function addresses*/

printf("x=%d y=%d\n", x, y); )

int*u, *v; /*u and v are pointers*/

temp=*u; /*temp is assigned the value pointed to by u*/

This function changes the values ​​of the variables x and y. By passing the addresses of the x and y variables to the function, we have given it the ability to access them. Using pointers and the (*) operation, the function was able to extract the values ​​placed in the corresponding memory locations and swap them.

Mainwhetherliterature: 1base, 2base

Additionalliteraturea: 10 extra

Test questions:

1. Can the names of formal and actual parameters of subprograms be the same?

2. What is the difference between a description of a procedure and a function?

3. What parameters are called formal and which are actual?

4. What are the styles for describing and defining functions?

5. Name the operator to return the result of the function execution?

A computer