No wonder I called this article “Functions as an integral part of programming”, because without them, in my opinion, no language has the right to exist. What is it? A function is the main building block of a well-written program. It not only makes it easier to read the code, but also radically changes the idea of structured programming. With the help of functions, you can reuse individual parts of the program by passing any parameters to them. No serious program can be imagined without this miracle of the programming element.

I'll tell you briefly how it works. A function is a block of instructions that your program can call. When accessing the header of this block (function name), it is executed and performs some actions specified by the programmer. After that, this block returns the received value and passes it to the main program. Let me explain in practice.

Roughly speaking, everything looks like this. I will briefly explain. We create some variable and assign it the result of executing the myfunc function, which in turn calculates the value of squaring some number. Functions are not executed immediately during program startup, but only when they are called. Maybe a little confusing, but that's how it is.

How to call a function?

In order to call a function, you need to create it. Although there are also built-in functions. For example, this: cos, sin, md5, count, abs and so on. To call them, you only need to assign the desired value to the variable.

A function argument is the value you pass to it when you call it. Function arguments are placed in parentheses. When you create a function, you specify the conditional names of the arguments. Then these names can be used in the function body as local variables. Let's return to the functions that the user creates himself. This is done very easily. First, the body of the function is created:

Function hello() ( echo "Hello, world!"; )

Then we call it. And if it has no parameters, then we just put parentheses. To call this function, we use only the line: hello();. Any function can also return a value using reserved word return. This statement terminates the execution of the function and sends the return value to the calling program. function sum($first, $second) ($r=$first + $second; return $r;) echo sum(2,5); the result of the program execution will be equal to 7. Local and global variables

As in any other programming language, there are variables that are only available inside the function and variables that are available in the code of the program itself. Such variables are called local and global respectively. Inside a function, you can't just access a variable that was created outside of that function. If you try to do this, you will create a new variable with the same name, but local to the function.

$per="Dima"; function primer() // Do: local variable output ( echo "My name is ".$per; ) echo primer();

In this case, the phrase "My name is" will appear on the screen. This means that inside the primer function, the $per variable was created and, by default, was assigned zero value. In order to avoid such jambs, you need to use the operator global. Let's fix the above code accordingly:

$per="Dima"; function primer() // Performs: global variable output ( global $per; echo "My name is ".$per; ) echo primer();

Everything should be fine now - problem solved. Just do not forget that if the function changes the value of an external variable, then such a change will affect the entire program, so you need to use this operator carefully!

Functions with two or more arguments

Some of the arguments passed to a function can be made optional, making the function less demanding. The following example shows this clearly:

... function font($text, $size=5) // Do: output font size ( echo " ".$text.""; ) font("Hello
",1); font("Hello
",2); font("Hello
",3); font("Hello
",4); font("Hello
",5); font("Hello
",6); font("Hello
");

By default, the font size is 5. If we omit the second parameter of the function, then it will be equal to this value.

Conclusion

Before I say goodbye, I want to draw your attention to one piece of advice. It consists in putting all the functions you have written into one file (for example, function.php). And then, in the file where you need to call the function, you just need to include function.php and everything will be ready for use. This will make it much easier to understand the logic in your program. To connect, use:

include_once("function.php");

require_once("function.php");

If you understand the essence of the issue under consideration in this article, then I am sure that you can easily use the functions in your programs. Once again, this is to make them more editable and reusable.

Functions over numbers. The VB language has the following mathematical functions: abs(x) - module calculation; sqr(x) - calculation of the square root, atn(x) - calculation of arc tangent; cos(x) - calculation of cosine; sin(x) - calculation of the sine; tan(x) - calculation of tangent; log(x) - calculation of the natural logarithm, exp(x) - calculation of the exponent, where x- function argument of numerical type. To calculate the values ​​of functions that are absent in the VisualBasic language, it is necessary to use formulas known from mathematics.

Expression y= in VB would be written like this: y=sin(x^2)+sqr(tan(x))*(x+5) ^ (1/5).

The function argument must be written in parentheses.

Functions for converting a value from one type to another. The VB programming language provides functions for changing the data type of a value. For example, there is a variable a of type Double and a variable s of type String.

To write a variable a to a variable s, it is necessary to perform a type conversion S=CStr(a), and to write a variable s to a variable a–a=CDbl(s).

VB functions for value type conversion:

CStr - convert to string;

CByte - conversion to Byte;

CInt - conversion toInteger;

CLng - conversion to Long;

CSng - conversion to Single;

CDbl - convert to Double.

2.6. Representation of various types of data in computer memory

To represent information in the computer memory (both numeric and non-numeric), a binary encoding method is used.

The elementary cell of computer memory has a length of 8 bits (bytes). Each byte has its own number (it is called address). The largest sequence of bits that a computer can process as a whole is called machine word. The length of a machine word depends on the processor word length and can be 16, 32, 64 bits, etc.

Character encoding. One byte is enough to encode characters. In this case, 256 characters can be represented (with decimal codes from 0 to 255). The character set of personal computers compatible with the IBM PC is most often an extension of the ASCII code (American Standard Code for Information Interchange - the standard American code for information interchange). Currently, two-byte representations of characters are also used.

Representation of integers in two's complement. The range of values ​​depends on the number of bits of memory allocated for their storage. n-bit memory can store different values. For example, values ​​of type Integer lie in the range from -32768 (-2 15) to 32767 (2 15 - 1) and 2 bytes (16 bits) are allocated for their storage; of type Long - in the range from -2 31 to 2 31 - 1 and are located in 4 bytes (32 bits).

For unsigned representation of integer binary numbers vary from 0 to
, and in signed representation - from
before
. In modern computers, it is customary to choose the length n of the bit grid of integers as a multiple of 8 (ie, an integer number of bytes).

In the case of representing a quantity with a sign, the leftmost (highest) digit indicates a positive number if it contains zero, and negative if it contains one.

The digits are numbered from right to left, starting from 0. In fig. .2.2 shows the numbering of bits in a two-byte machine word.

Rice. 2.2. Hbit scaling in a two-byte machine word

Additional code positive number is the same as its direct code. The direct code of an integer can be obtained as follows: the number is translated into binary system reckoning, and then its binary notation on the left is supplemented with as many insignificant zeros as required by the data type to which the number belongs.

For example, if the number 37 (10) = 100101 (2) is declared as an Integer value (sixteen-bit signed), then its direct code will be 0000000000100101, and if it is a Long value (thirty-two-bit signed), then its direct code will be. For a more compact notation, the hexadecimal representation of the code is more often used. The resulting codes can be rewritten as 0025 (16) and 00000025 (16) respectively.

The additional code of a negative integer can be obtained using the following algorithm:

    write down the direct code of the module of the number;

    invert it (replace ones with zeros, zeros with ones);

    add one to the inverse code.

For example, let's write the two's complement code of -37, interpreting it as a Long (32-bit signed) value:

    the direct code for the number 37 is ;

    inverse code;

    additional code or FFFFFFDB (16) .

When obtaining a number by its additional code, first of all, it is necessary to determine its sign. If the number turns out to be positive, then simply translate its code into a decimal number system. In the case of a negative number, the following algorithm must be performed:

    subtract the number 1 from the code;

    invert code;

    translate into decimal system reckoning. Write the resulting number with a minus sign.

Examples. Let's write down the numbers corresponding to additional codes:

    0000000000010111. Since zero is written in the most significant bit, the result will be positive. This is the code for the number 23.

    1111111111000000. The code of a negative number is written here. We execute the algorithm: 1) 1111111111000000 (2) - 1 (2) = 1111111110111111 (2) ; 2) 0000000001000000; 3) 1000000 (2) = 64 (10) . Answer: -64.

Objective: 1) study the rules for describing functions; 2) acquire the skills of using functions when writing programs in C++.

Theoretical information

The main unit of programs in the C++ language is a function.

Function- a logically completed, in a certain way designed fragment of a program that has a name. Functions allow you to divide large computational tasks into smaller ones.

Every C++ program necessarily contains a function called main, which is the body of the program. For all other functions, if they are present in the program, prototypes should be declared - schematic representations that tell the compiler the name and form of each function in the program.

Syntax for function prototype with parameters:

return_value_type function_name (list_of_parameters_with_indication_of_types);

Functions in C++ are standard (library) and user-programmable.

Standard Features

Descriptions of standard functions are found in files included in the program using the #include directive. Such files are called header; they have the extension h.

Referencing a function name in the main program is called a function call.

Calling functions leads to the performance of some actions or the calculation of some value, which is then used in the program.

y=sin(x); //sine calculation function

Function definition

In general, functions are defined as follows:

return_value_type function_name (type parameter_name,...,type parameter_name)

function_body

Programmable Features

Functions that a programmer creates himself simplify the process of writing programs, because they:

    help to avoid re-programming, since the same function can be used in different programs;

    increase the level of modularity of the program, therefore, it is easier to read, modify and correct errors.

Example9 .1. Let's create a function that prints 65 characters "*" in a row. To make this function work in some context, it is included in the letterhead printing program. The program consists of functions: main() and stars().

// letterhead

#include

const int Limit=65;

void stars(void); // stars() function prototype

cout<<"Moscow Institute of Electronic Engineering"<

// Defining the stars() function

for (count=1; count<=Limit; count++)

We looked at an example of a simple function that has no arguments and does not return any values.

Function parameters

Consider the use of function parameters as an example.

Example9. 2. Let's write the space() function, whose argument will be the number of spaces that this function should print.

#define address " Zelenograd"

#define name "Moscow Institute of Electronic Engineering"

#define department "Informatics and Programming"

const int LIMIT=65;

#include

void space(int number);

cout<

spaces=(LIMIT - strlen(name))/2; // Calculate how much

// need spaces

cout<

space((LIMIT - strlen(department))/2); // argument is an expression

cout<

// Definition of the stars() function

for (count=1; count<=LIMIT; count++)

// Definition of the space() function

void space(int number)

for (count=1; count<=number; count++)

The variable number is called the formal argument. This variable takes on the values ​​of the actual argument when the function is called. In other words, formal argument is a variable in the definition of the called subroutine, and actual argument- the specific value assigned to this variable by the calling program.

If more than one argument is required to communicate with a certain function, then along with the function name, you can specify a comma-separated list of arguments:

void printnum (int i, int j)

( cout<<"Координаты точек”<< i << j <

The input value of the function can be processed due to the presence argument; the output value is returned using the return keyword.

A separate system (subsystem, subprogram), which receives control inputs in the form of argument values. At the output, the function returns a result, which can be either a scalar value or a vector value (structure, index array, etc.). During the execution of the function, some changes can also be made in the managed system, both reversible and irreversible.

Side effect

Functions and Procedures

In some programming languages ​​(for example, in Pascal), functions and procedures (subroutines that do not return values) are clearly distinguished by the syntax of the language. In others - for example, in the C language - procedures are a special case (subset) of functions that return a value of type (pseudotype) void - an empty value.

Arguments and Options

When a function is called, arguments are passed to it. If the argument is a reference to a memory area (variable, pointer or reference), then the function, depending on the type of its parameter, can either use its value (for example, create a variable, copy the argument value there), or the argument itself (create a reference to the area the memory referenced by the argument).

Function with no arguments

Such a function does not require any arguments.

see also

Links

  • PHP functions. Syntax and Examples of Using PHP Functions

Wikimedia Foundation. 2010 .

See what "Function (programming)" is in other dictionaries:

    Wiktionary has the article "function" Function is a polysemantic term that means a relationship between elements in which a change in one entails a change ... Wikipedia

    A stub function in programming is a function that does not perform any meaningful action, returns an empty result or input data unchanged. The equivalent English word is stub. Used: For clarity when ... ... Wikipedia

    higher psychic function: recovery- (restoration of higher mental functions) a section of neuropsychology devoted to the study of mechanisms and methods for restoring the functions of higher mental functions, impaired due to lesions of the local brain of the brain. Based on ideas about... Great Psychological Encyclopedia

    Mathematical programming is a mathematical discipline that studies the theory and methods for solving problems of finding extrema of functions on sets of a finite-dimensional vector space determined by linear and nonlinear constraints ... ... Wikipedia

    In the field of computerization, the concept of programming network tasks, or otherwise called network programming, is quite similar to the concepts of socket programming and client-server programming, ... ... Wikipedia

    A higher-order function is a function that takes other functions as arguments or returns another function as a result. The basic idea is that functions have the same status as other data objects. ... ... Wikipedia

    PROGRAMMING MATHEMATICAL- complex mathematical. models and methods for solving problems of finding the extremum (maximum or minimum) of functions of several variables under constraints in the form of inequalities. It means that the variables characterize some aspects of the mechanism ... ... Russian sociological encyclopedia

    Mathematical discipline that studies mathematics. abstractions of programs, treated as objects expressed in a formal language, with a certain information and logical. structure and subject to execution on automatic. devices. P. t. ... ... Mathematical Encyclopedia

    A function in programming is a type of subroutine. The feature that distinguishes it from another kind of procedure subroutines is that the function returns a value, and its call can be used in the program as an expression. From the point of view ... ... Wikipedia

    PROGRAMMING, MATH- a branch of applied mathematics used as a method in economic research. Develops the theory and methods for solving conditional extremal problems, is the main part of the formal apparatus for analyzing various control problems ... Big Economic Dictionary

If you are a developer like me, then you probably learned the OOP paradigm first. Your first language was Java or C++ - or, if you're lucky, Ruby, Python, or C# - so you probably know what classes, objects, instances, etc. are. What you definitely don't really understand is the basics of that strange paradigm called functional programming, which differs significantly not only from OOP, but also from procedural, prototype-oriented and other types of programming.

Functional programming is becoming popular - and for good reason. The paradigm itself is not new: Haskell is perhaps the most functional language, and it originated in the 90s. Languages ​​such as Erlang, Scala, Clojure also fall under the definition of functional. One of the main advantages of functional programming is the ability to write programs that work concurrently (if you already forgot what it is - refresh your memory by reading), and without errors - that is, deadlocks and thread safety will not bother you.

Functional programming has many advantages, but the possible maximum use of CPU resources due to competitive behavior is its main advantage. Below, we'll look at the basic principles of functional programming.

Introduction: All of these principles are optional (many languages ​​do not fully follow them). All of them are theoretical and are needed for the most accurate definition of the functional paradigm.

1. All functions are clean

This rule is certainly the main one in functional programming. All functions are pure if they satisfy two conditions:

  1. A function called with the same arguments always returns the same value.
  2. There are no side effects during the execution of the function.

The first rule is clear - if I call the sum(2, 3) function, I expect the result to always be 5. As soon as you call the rand() function, or access a variable that is not defined in the function, the purity of the function is violated, and this not allowed in functional programming.

The second rule - no side effects - is broader in nature. A side effect is a change to something other than the function that is currently executing. Changing a variable outside the function, writing to the console, throwing an exception, reading data from a file are all examples of side effects that take away from the purity of a function. This may seem like a serious limitation, but think again. If you are sure that calling a function will not change anything “outside”, then you can use this function in any scenario. This paves the way for competitive programming and multi-threaded applications.

2. All functions are first class and higher order

This concept is not a feature of FP (it's used in Javascript, PHP, and other languages) - but it's a requirement. In fact, Wikipedia has an entire article dedicated to first-class functions. For a function to be first-class, it must be able to be declared as a variable. This allows the function to be manipulated as a normal data type and still be executed.

3. Variables are immutable

Everything is simple here. In functional programming, you cannot change a variable after it has been initialized. You can create new ones, but you can't change existing ones - and thanks to this you can be sure that no variable will change.

4. Relative transparency of functions

It is difficult to give a correct definition of relative transparency. I think the most accurate is this: if you can replace a function call with a return value, and the state does not change, then the function is relatively transparent. This may be obvious, but I will give an example.

Let's say we have a Java function that adds 3 and 5:

Public int addNumbers()( return 3 + 5; ) addNumbers() // 8 8 // 8

Obviously, any call to this function can be replaced by 8, which means that the function is relatively transparent. Here is an example of an opaque function:

Public void printText()( System.out.println("Hello World"); ) printText() // Returns nothing, but prints "Hello World"

This function does not return anything, but it prints text, and if the function call is replaced with nothing, the console state will be different - which means that the function is not relatively transparent.

5. Functional programming is based on lambda calculus

Functional programming relies heavily on a mathematical system called the lambda calculus. I'm not a mathematician, so I won't go into details - but I want to point out two key principles of lambda calculus that form the very concept of functional programming:

  1. In the lambda calculus, all functions can be anonymous, since the only meaningful part of the function header is the argument list.
  2. When called, all functions go through a process of currying. It is as follows: if a function is called with several arguments, then at first it will be executed with only the first argument and will return a new function containing 1 less argument, which will be immediately called. This process is recursive and continues until all arguments have been applied, returning the final result. Since the functions are pure, this works.

As I said, the lambda calculus does not end there - but we have only covered the key aspects related to FP. Now, in a conversation about functional programming, you can flash the word “lambda calculus”, and everyone will think that you are fumbling 🙂

Conclusion

Functional programming is a real brain strain - but it's a very powerful approach and I believe its popularity will only grow.

If you want to learn more about functional programming, then we advise you to check out the examples of using the principles of FP in JavaScript ( , ), as well as the one dedicated to functional C#.