Differences between function declaration and function expression in javascript. Function Declaration

As a C language object, a function must be declared. Declaring a user function, i.e. its declaration is carried out in two forms - in the form of a description and in the form of a definition.

The description of a function consists of giving the program file of its prototype first. The function prototype informs the compiler that its full definition (its full text) will be given later in the program text: in the current or another source file, or located in the library.

The language standard uses the following method of declaring functions:

result_type ID _functions(variable type1, ..., variable type N);

Note that it is not necessary to specify variable identifiers in prototype parentheses, since the language compiler does not process them.

The prototype description allows the compiler to check that the types and number of parameters match when the function is actually called.

An example of a fun function description with a list of parameters:

float fun(int, float, int, int);

The complete definition of the function is as follows:

result_type ID _functions (parameter list)

function code

The result type determines the type of expression whose value is returned to the point of its call using the operator return<выражение> .

If a function type is not specified, the default type is assumed int .

The parameter list consists of a list of parameter types and parameter identifiers, separated by commas.

The function may not have parameters, but parentheses are required in any case.

If a function does not return any value, it must be declared as a function of type void (blank).

In this case the operator return you don't have to put it.

A function can have multiple statements return , but there may not be any. In such cases, return to the calling program occurs after the last statement in the function is executed.

An example of a function that determines the smallest value of two integer variables:

int min (int x, int y)

return(x

All functions that return a value must be used on the right side of C expressions, otherwise the returned result will be lost.

If a function does not have a list of parameters, then when declaring such a function, it is advisable to also indicate the void keyword in parentheses. For example, void main(void).

Expressions in JavaScript are combinations operands And operators.

Operations in expressions are executed sequentially in accordance with the priority value (the higher the priority value, the higher it is). The returned result is not always of the same type as the type of data being processed. For example, comparison operations involve operands of different types, but the return result will always be a boolean type.

Rice. 1. Expression structure in JavaScript

Operands is the data processed by the JavaScript script. The operands can be either simple or complex data types, as well as other expressions.

Operators are language symbols that perform various operations with data. Operators can be written using punctuation characters or keywords.

Depending on the number of operands, the following types of operators are distinguished:
unary— one operand is involved in the operation;
binary— the operation involves two operands;
ternary— combines three operands.

The simplest form of expression is literal— something that evaluates to itself, for example, the number 100, the string "Hello world" . A variable can also be an expression, since it evaluates to the value assigned to it.

Expressions and Operators in JavaScript

1. Arithmetic operators

Arithmetic operators designed to perform mathematical operations, they operate on numeric operands (or variables that store numeric values), returning a numeric value as a result.

If one of the operands is a string, the JavaScript interpreter will try to convert it to a numeric type and then perform the appropriate operation. If type conversion is not possible, the result will be NaN (not a number).

Table 1. Arithmetic operators
Operator/Operation Description A priority
+ Addition Adds numeric operands. If one of the operands is a string, then the result of the expression is a string. 12
- Subtraction Subtracts the second operand from the first. 12
- Unary minus Converts a positive number to a negative number and vice versa. 14
* Multiplication Multiplies two operands. 13
/ Division Divides the first operand by the second. The result of division can be either an integer or a floating point number. 13
% Modulo division (division remainder) Calculates the remainder resulting from an integer division of the first operand by the second. Applies to both integers and floating point numbers. 13
var x = 5, y = 8, z; z = x + y; // return 13 z = x - y; // return -3 z = - y; // return -8 z = x * y; // return 40 z = x / y; // return 0.625 z = y % x; // return 3

2. Assignment operators

Assignment Operators are used to assign values ​​to variables. Combined operators allow you to store the original and subsequent values ​​in a single variable.

var a = 5; // assign the numeric value 5 to variable a var b = "hello"; // store the string hellow in variable b var m = n = z = 10; // assign the variables m, n, z the numerical value 10 x += 10; // equivalent to x = x + 10; x -= 10; // equivalent to x = x - 10; x *= 10; // equivalent to x = x * 10; x /= 10; // equivalent to x = x / 10; x %= 10; // equivalent to x = x % 10;

3. Increment and decrement operators

Operations increment and decrement are unary and increment and decrement the value of the operand by one. The operand can be a variable, an array element, or an object property. Most often, such operations are used to increment a counter in a loop.

var x = y = m = n = 5, z, s, k, l; z = ++x * 2; /* as a result of calculations will return the value z = 12, x = 6, i.e. the value of x is first increased by 1, and then the multiplication operation is performed */ s = y++ * 2; /* as a result of calculations will return the value s = 10, y = 6, i.e. First, the multiplication operation is performed, and then the value increased by 1 is stored in the variable y */ k = --m * 2; // return the value k = 8, m = 4 l = n-- * 2; // return the value l = 10, n = 4

4. Comparison operators

Comparison Operators are used to match operands, the result of the expression can be one of two values ​​- true or false . Operands can be not only numbers, but also strings, logical values ​​and objects. However, comparisons can only be performed on numbers and strings, so operands that are not numbers or strings are converted.

If both operands cannot be successfully converted to numbers or strings, the operators always return false .

If both operands are strings/numbers or can be converted to strings/numbers, they will be compared as strings/numbers.

If one operand is a string/converts to a string and the other is a number/converts to a number, then the operator will attempt to convert the string to a number and perform a number comparison. If the string is not a number, it is converted to NaN and the result of the comparison is false .

Most often, comparison operations are used when organizing branches in programs.

Table 4. Comparison operators
Operator/Operation Description A priority
== Equality Tests two values ​​for the same value, allowing type conversion. Returns true if the operands are the same, and false if they are different. 9
!= Inequality Returns true if the operands are not equal 9
=== Identity Tests two operands for "identity" using a strict definition of a match. Returns true if the operands are equal without type conversion. 9
!== Non-identity Performs identity verification. Returns true if the operands are not equal without type conversion. 9
> More Returns true if the first operand is greater than the second, otherwise returns false. 10
>= Greater than or equal to Returns true if the first operand is not less than the second, otherwise returns false. 10
Returns true if the first operand is less than the second, otherwise returns false. 10
Returns true if the first operand is not greater than the second, otherwise returns false. 10
5 == "5"; // return true 5 != -5.0; // return true 5 === "5"; // return false false === false; // return true 1 !== true; // return true 1 != true; // will return false since true is converted to 1 3 > -3; // return true 3 >= "4"; // return false

5. Logical operators

Logical operators allow you to combine conditions that return boolean values. Most often used in an if conditional statement.

(2 < 3) && (3===3); // вернет true, так как выражения в обеих скобках дают true (x < 10 && x >0); // will return true if x is in the range from 0 to 10 !false; // return true

6. Bitwise operators

Bitwise operators operate on the operands as a 32-bit sequence of zeros and ones and return a numeric value indicating the result of the operation, written in decimal notation. Integer numbers are considered as operands; the fractional part of the operand is discarded. Bitwise operations can be used, for example, when encrypting data, working with flags, and delineating access rights.

Table 6. Bitwise operators
Operator/Operation Description A priority
& Bitwise AND If both bits are 1, then the resulting bit will be 1. Otherwise the result is 0. 8
| Bitwise OR If one of the operands contains a 1 at position, the result will also contain a 1 at that position, otherwise the result at that position will be 0. 6
^ Exclusive OR If one and only one value contains a 1 at any position, then the result will contain a 1 at that position, otherwise the result at that position will be 0. 7
~ Denial A bitwise negation operation is performed on the binary representation of the value of an expression. Any position containing a 1 in the original expression is replaced with a 0. Any position containing 0 in the original expression becomes 0 . Positive numbers start at 0, negative numbers start at -1, so ~ n == -(n+1) . 14
The operator shifts the bits of the first operand to the left by the number of bit positions set by the second operand. Zeros are used to fill positions on the right. Return a result of the same type as the left operand. 11
>> Bitwise shift right The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Digits shifted outside the range are removed. The most significant bit (32nd) is not changed to preserve the sign of the result. If the first operand is positive, the most significant bits of the result are filled with zeros; if the first operand is negative, the most significant bits of the result are filled with ones. Shifting a value to the right by one position is equivalent to dividing by 2 (discarding the remainder), and shifting to the right by two positions is equivalent to dividing by 4, etc. 11
>>> Bitwise right shift without sign The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Zeros are added to the left, regardless of the sign of the first operand. Digits shifted outside the range are removed. 11
var x = 9, y = 5, z = 2, s = -5, result; // 9 is equivalent to 1001, 5 is equivalent to 0101 result = x & y; // will return 1 (equivalent to 0001) result = x | y; // will return 13 (equivalent to 1101) result = x ^ y; // return 12 (equivalent to 1100) result = ~ y; // will return -6 (equivalent to 1100) result = x<< y; // вернет 288 (эквивалентно 100100000) result = x >> z; // return 2 (equivalent to 10) result = s >>> z; // will return 1073741822 (equivalent to 1111111111111111111111111111110)

7. String Operators

There are several operators that work with strings in special ways.

"1" + "10"; // return "110" "1" + 10; // returns "110" 2 + 5 + "colored pencils"; // returns "7 colored pencils" "Colored pencils" + 2 + 5; // returns "25 colored pencils" "1" > "10"; // return false "10"<= 10; // вернет true "СССР" == "ссср"; // вернет false x = "micro"; x+= "soft"; // вернет "microsoft"

8. Special operators

Table 8. Special operators
Operator/Operation Description A priority
. Accessing a property Accesses a property of an object. 15
,Multiple calculation Evaluates multiple independent expressions written on one line. 1
Array indexing Accesses array elements or object properties. 15
() Function call, grouping Groups operations or calls a function. 15
typeof Data type definition Unary operator, returns the data type of the operand. 14
instanceof Checking the type of an object The operator checks whether an object is an instance of a particular class. The left operand must be an object, the right operand must contain the name of the object class. The result will be true if the object on the left is an instance of the class on the right, false otherwise. 10
in Checking for the presence of a property The left operand must be a string and the right operand must be an array or object. If the left value is a property of an object, the result will be true . 10
new Creating an object The operator creates a new object with undefined properties, then calls the constructor function to initialize it (passing parameters). Can also be used to create an array. 1
delete Delete The operator allows you to remove a property from an object or an element from an array. Returns true if the deletion was successful, false otherwise. When an array element is deleted, its length does not change. 14
void Defining an expression without a return value Unary operator, discards the value of the operand and returns underfined . 14
?: Conditional expression operator The ternary operator allows you to organize simple branching. The expression involves three operands, the first must be a Boolean value or convert to one, and the second and third must be any values. If the first operand is true , then the conditional expression will take the value of the second operand; if false - then the third one. 3
document.write("hello world"); // displays the string hello world i = 0, j = 1; // stores values ​​in variables function1(10, 5); // function call function1 with parameters 10 and 5 var year = ; // creates an array with elements typeof (a:1); // return "object" var d = new Date(); // create a new object using the Date() constructor d instanceof Date; // return true var mycar = (make: "Honda", model: "Accord", year: 2005); "make" in mycar; // return true var obj = new Object(); // creates an empty object var food = ["milk", "bread", "meat", "olive oil", "cheese"]; delete food; // removes the fourth element from the array food x > 10 ? x * 2: x / 2; // returns x * 2 if x > 10, otherwise x / 2

9. Comments in JavaScript

Single-line comment: precede the comment text with the characters // .

There are many ways to do the same thing in JavaScript. There is both good and bad in this. For a beginner, this is definitely bad, since he will not only have to study more information, but there will also be more places for potential mistakes to be made. This can happen when defining functions.

There are many different ways to declare a function:

Function A() (); // function declaration var B = function () (); //function expression var C = (function () ()); // function expression with grouping operator var D = function foo () (); // named function expression var E = (function () ())(); // self-invoking function expression var F = new Function(); // function constructor var G = new function() (); // degenerate case: object constructor
It’s hard not to get confused in such abundance, isn’t it? Typically, in everyday life we ​​use no more than three different types of function declarations, and this works great. However, if you dig deeper, it may turn out that most of us do not even suspect how many mysteries and pitfalls the operation of declaring a function contains.

According to the ECMA documentation, the syntax for defining a function is as follows:
Function Declaration: function Identifier (Parameters) (Function Body) Function Expression: function Identifier (optional) (Parameters) (Function Body)
Although these definitions look quite similar, there is a big difference between a function declaration and a functional expression. Function declaration ( Function Declaration) is created before any code is executed, while a function expression ( Function Expression) will be created only when the interpreter reaches this line of code.

A function expression is a declaration of a function in the context of an expression.

Let's look at some examples of function expressions:

Assignment operator
var a = function()();
This is a classic example of specifying a functional expression through assignment. The assignment operator expects an expression on the right, which is why the function becomes part of the expression.
With a little imagination, you can come up with the following examples:

Var a = function() ( return 1; )() + 12; // 13 var b = function() ( return 1; ) + ""; // function ()(return 1) var c = function() ( return 1; ) + "" - 1; //NaN

Grouping operator
By declaring a function, we cannot execute it immediately, however, by wrapping the function declaration in parentheses, this becomes possible. The grouping operator is expressed in parentheses, and in this case it turns a function declaration into a function expression.

Function foo() ( return 1; ) // undefined function foo() ( return 1; )(); // Uncaught SyntaxError: Expected () to start arrow function, but got ")" instead of "=>" (function foo() ( return 1; )()) // 1 (function foo() ( return 1; ) )() // 1
There is no fundamental difference between the third and fourth options, since in the first case we execute an expression that defines and immediately executes a function, and in the second case we execute an expression that defines a function that will then be executed.

Comma operator
The comma operator evaluates the value of each of its operands (from left to right) and returns the value of the last operand.

0, function() ( return 1; )(); // 1

Operators (+, -, !, ~, void)
+function() ( return false; )(); // 0 -function() ( return false; )(); // -0 !function() ( return false; )(); // true ~function() ( return false; )(); // -1 void function() ( return false; )(); //undefined
Combined operators:
!-function () ( return false; )(); // true var c = 5 * (2 - function () (return 1)()) // 5 var c = 5 * 2 - -~function () (return 1)() // 8

The difference between named function expressions and unnamed ones:

Often, the name assigned to a function expression is redundant in the context of the rest of the code, unless the function must be accessed from within the function itself. The scope of a function expression name is limited solely to the function itself.

Var f = function getFactorial (n) ( return n ? n * getFactorial(n - 1) : 1; ); f(5); // 120

Important:
Remember, you're writing code for people, so try to avoid writing ninja-style code. The knowledge presented in the article is useful in order to understand the internal structure of the language and not get confused if you suddenly come across such expressions in one of the projects or at an interview.

In the previous sections, we looked at those elementary “building blocks” (operators and expressions) from which a program is built. In early programming languages, such as the first versions of Basic, this was where it ended. A program is a sequence of statements, that's all. As long as the programs are small, this approach is quite workable. If there are 10 statements in a program, then no additional structure is needed. But if there are 10,000 operators or 10,000,000 operators in a program (and such programs exist, and they work), then it is impossible to do without introducing an additional structure.

VBA supports the following program structure. At the highest level of the hierarchy is the application, then there are projects associated with the actual documents of that application, and at the third level there are modules (application modules, user modules, class modules, form modules and link modules). And at the last level there are procedures and functions of these modules.

This structuring of programs fully satisfies the principles of structured and modular programming. In this section we will discuss in detail work at the module level; we will talk about working with applications and projects See Section 20.6, "Visual Basic for Application Editor."

So, module - This is part of the program, designed in a form that allows its independent broadcast. The module in turn consists of two sections: classifieds section(Declarations) And procedures and functions section. In chapter Declarations describes global variables, user-defined types, and enumerated types. The next section describes the procedures and functions. Procedure is a minimal semantically complete software construction that can be executed. In the end, operators are not simply executed or written; they are found in the description of procedures and functions.

Area of ​​visibility - This is the area of ​​the program where the name of a variable is visible and therefore its value can be accessed.

There are three levels of visibility and five ways of advertising:

Procedure (the scope is only the procedure in which the variable is declared).

  • The Dim statement declares a variable within the body of a procedure and anywhere in the procedure but before the statements that use it. The lifetime of a given variable is the scope of the procedure, i.e., when entering a given procedure, memory is allocated for the variable and it is initialized, then, during the execution of the procedure, the value of the variable can change, after exiting the procedure, the allocated memory is freed, and, Accordingly, the value of the variable is lost.
  • The static operator is antagonistic to the Dim operator; it declares a static variable. The difference is that when exiting a procedure, the memory of a static variable is not taken away, but becomes (due to scope) temporarily unavailable, and accordingly, its value is saved, which can be used when calling the procedure again.

Module (scope - all procedures of the module in which the variable is declared):

  • The Private statement declares a variable in the declarations section Declarations(outside module procedures).
  • The Dim operator is absolutely similar (in this case) to the Private operator.

Application (scope - all procedures of all modules of the active application):

  • The Public statement declares a variable in the declarations section Declarations.

Procedures, like all VBA user-defined elements, require declarations. A procedure declaration has the following syntax:

Sub procedurename([argumentlist])

[blockOperators1]

[ blockOperators2 ] End Sub

The Private keyword sets the following scope for a procedure - only the module in which it is described. That is, it can only be called by procedures of the same module. The Public keyword, on the contrary, declares the procedure accessible to all project modules. By default, the procedure is publicly available, that is, it has the Public status. As for the use of the Friend keyword, we will talk about it a little later when we talk about VBA classes.

Following the declaration statements is the optional static keyword, which defines all local variables as static. This operator is equivalent to declaring each of the variables described in the body of the procedure as static.

ProcedureName is a procedure identifier that satisfies all naming rules.

The name is followed by mandatory parentheses, but an optional Argument-List. Let's take a closer look at the single argument declaration; if there are more, they are simply separated by a comma.

Argument-Name [()] [=Default]

The Optional keyword means that the argument is optional and can be omitted when calling the procedure. By default, the argument is required. All optional arguments must come after the required ones. Naturally, the optional parameter valueDefault is the value of the optional argument if it is not specified when calling the procedure. If the construct includes the ParamArray keyword, then the Optional keyword cannot be used.

As actual parameters, a procedure can receive not only the values ​​of constants, but also the values ​​of variables. When passing variables to a procedure as parameters, one of two methods can be used: ByVal (by value) and ByRef (by reference).

To understand the difference between these two methods, you need to consider the storage and mechanism for passing parameters “from the inside”. So, when declaring a variable of any type, an area in the computer memory is allocated in which the value of the variable will be stored. The size of this area, of course, depends on the type of this variable. Now, knowing how a variable is structured inside a computer, let's consider passing it as a parameter to a procedure.

If a variable is passed to a procedure by reference (that is, by using the ByRef keyword in front of its name), then the procedure will be passed the address of this variable in memory. In this case, the formal argument of the procedure is identified with the actual parameter passed.

Thus, the called procedure, changing the value of the formal parameter, changes the value of the variable.

If a variable is passed by value (that is, using the Byval keyword before its name), then the compiler creates a temporary copy of this variable and it is the address of this copy variable that is passed to the procedure. Thus, the called procedure, changing the value of the formal parameter, changes the value of the copy variable (but not the variable itself), which will be destroyed after the procedure completes. By default, in VBA, variables are passed by reference.

After looking at ways to pass variables to a procedure, let's move on to a further look at its design. The following paramArray parameter may appear only before the last argument in the argument list, indicating that it is an optional array of elements of type variant.

Argument name - it is an identifier, constructed according to naming conventions, that represents an argument in the body of a procedure. Parameter data type is either a built-in data type or a user-defined type. Default Data type is Variant.

After the description of the procedure comes blockOperators1(usually called body of the procedure), in which the values ​​of the procedure's arguments can be used. If during the execution of procedure statements an Exit Sub statement (exit from the procedure) is encountered, then execution of the procedure is terminated and control is transferred to the statement following the procedure call statement.

A function differs from a procedure in that in addition to executing statements, it returns a value. The syntax for describing a function is slightly different from a procedure:

Function Functionname [(argument list)]

[blockOperators1]

[Function name = Expression]

[blockOperators2]

[Function name = Expression] End Function

First, the sub keyword has been replaced with Function. Secondly, after declaring the arguments, you must indicate the type of value returned by the function. Thirdly, in the body of the function there is an assignment to the function name of any value that has a declared type. Of course, such an assignment is not necessary, but then your function will look like a procedure, and the result of the function will be the default value defined for the corresponding type. Finally, instead of the Exit Sub keyword, the Exit Function keyword is used to exit a function.

Let's use the example of a publishing house and stores to describe the procedure for initializing an array of applications. So we have an array argument that is passed to the procedure, and the procedure initializes it using the standard inputBox function. To determine the upper and lower bounds of the array, the standard functions LBound and uBound are used.

In the case of the function, an array of requests and the number of books in stock are entered as arguments, and the logical value True is returned if the requests of all stores are satisfied, and False otherwise. By the way, we will make the number of books argument optional, defaulting to 5000.

Program 20.14. Declaring Procedures and Functions

Public Sub InitBookShops(arr() As Integer)

Dim i, str For i = LBound (arr) To UBound (arr)

str = "Enter order for store #" & i arr(i) = InputBox(str) Next i End Sub

Public Function SaleAbility(arr() As Integer, _ "

Optional numOfBooks As Integer = 5000) As Boolean

For Each elem In arr

sumOfBooks = sumOfBooks + elem Next If sumOfBooks< numOfBooks Then

SaleAbility = True Else

SaleAbility = False End If End Function

Comment

There is deliberate irrationality in the body of the SaleAbility function. Instead of the last conditional if statement. . .Then. . .Else you can and should write an equivalent, more efficient assignment operator SaleAbility = sumOfBooks< numOfBooks. Этим замечанием мы специально акцентируем внимание читателя на подобных мелких, но важных "хитростях" хорошего стиля программирования.

In addition to the declaration of procedures and functions described above, there is a special type of procedure in VBA. These are procedures for responding to an event caused by the system or user (See Chapter 22 "Developing an Application"). For example, for Word documents the open and close events are defined, for Excel workbooks - Beforesave and Beforedose, for objects of user classes - initialize and Terminate, clicking a dialog box button is also an event, etc. The user can create a procedure for reacting to such events himself. , for example, ask to display the message “Goodbye, thanks for your work!” when closing the document.

The syntax of such a procedure is the same as that of an ordinary one, only its name first indicates the object with which the event will be associated, then the underscore character (_), and then the actual name of the event.

Program 20.15. Event response procedure

Private Sub Document_Close()

MsgBox ("Goodbye, thanks for your work!")

Comment

Event driven is a way of structuring program code based on the following idea. There is a certain predefined set of named events. Events can be explicitly associated with objects, or they can be associated implicitly or be associated with implicit objects, in the latter case events are usually called system events. Events may occur. The occurrence of an event implies that the state of the system has changed in a certain way. An event may have a procedure associated with it, called an event response. When an event occurs, the reaction procedure is automatically called. Modern programming systems that support event control provide for a large number of different events, reactions to which can be defined in the program, for example: pressing a key on the keyboard, hitting the mouse pointer in a certain area of ​​the screen, reaching a specified value by an internal timer, opening a specified file, and etc. In a completely event-driven program, there is no main flow of control; it is located outside the program (in the operating system or in the administrative runtime system, i.e., where the mechanism for generating events is implemented). Control enters the program only in the form of calling a reaction procedure. This organization of the program ensures high modularity, transparency, balanced structure and other useful properties. It is clear that if you associate events with application commands (as is usually done), then event management is the best suited for implementing the user interface.


Modern programming systems have rich and ever-evolving libraries of ready-made components, which are called controls and are tightly integrated with built-in event control mechanisms. Using ready-made controls is convenient, productive, and should be recommended in most cases. For more information on this topic, see Chapter 22, Application Development.

Naturally, in addition to declaring procedures and functions, they need to be used - called. There are several ways to do this, and “several” is an understatement. VBA provides the user with such a flexible system for calling procedures and functions that he has to think about what what one of the ways to call a procedure.

The first, simplest call:

NameProcedureListActualParameters

ProcedureName -this is your Called Procedure as wellList of ActualPair - meters - this is the list of actual parameters passed to the procedure when it is called. It must match the required argument list specified when the procedure is declared. Actual parameters, if there are more than one, are listed separated by commas; their order must correspond to the declared arguments. Note that when calling a procedure like this, there is no need to enclose the list of actual parameters in parentheses.

You can also call a procedure using the Call keyword: Call Procedure name (List of Actual Parameters)

The essence of all parameters with this method of calling remains the same. The difference is that the list of actual parameters must be enclosed in parentheses.

Calling a function is slightly different from calling procedures. The main difference is that you can pass the calculated value of a function to some variable, so the function call looks like this:

VariableName = FunctionName (List of Actual Parameters)

Let's use the above procedures and functions as an example to show how they are called.

Program 20.16. Calling procedures and functions

Dim bookshops(1 To 25) As Integer Dim result As Boolean

result = SaleAbility(bookshops, 3000)

MsgBox(result) End Sub

In the calling methods discussed, the actual parameters were placed in the same sequence as the formal arguments when declaring a procedure or function. In some cases, especially when a procedure contains a large number of optional arguments, you can use a unique VBA feature - named arguments. With such a call, in addition to the value of the actual parameter, the name is also specified

formal argument to which the given value corresponds. To do this, the argument name is followed by a colon and an equal sign, followed by the actual parameter. This is a very convenient technique that allows you to see the relationship between an argument and an actual parameter.

Program 20.17. Using Named Arguments

Dim bookshops(1 To 25) As Integer

Dim result As Boolean

result = SaleAbility(arr:= bookshops, numOfBooks:= 3000)

MsgBox(result) End Sub

When describing the procedure declaration syntax, we briefly mentioned the ParamArray keyword; it is time to give it its due attention. The ability to pass a previously unknown number of actual parameters to a procedure is again unique to many other programming languages.

For example, we will create a procedure for counting the total number of applications using the ParamArray parameter. When calling this procedure in the Tests procedure, you can specify as many actual parameters of the array of requests as you like.

Program 20.18. Using the ParamArray Parameter

Sub FullSum(ParamArray arr() As Variant)

Dim sum As Integer

For i = LBound(arr) To UBound(arr) sum = sum + arr(i)

MsgBox (sum) End Sub

FullSum 100, 2000, 350, 450 End Sub

Let's consider another way to call procedures or functions - a recursive call, i.e. a call in which the procedure is called from its own body. A standard example of a recursive function is the calculation of a factorial.

Program 20.19. Recursive function call

Function fctrl(n As Integer) As Variant

If(n<= 1) Then fctrl = 1

fctrl = n * fctrlfn - 1) End If End Function

MsgBox fctrl(20) End Sub

As a rule, recursive calls should not be overused, since recursive calls quickly fill up the computer's stack memory and take much more time to process them. In our case, we can avoid using a recursive call by replacing it with an ordinary loop. Although, of course, there are situations where the use of recursive methods significantly speeds up work, for example, when working with tree data structures.

Finally, we'll look at an example that shows the difference between passing parameters by reference and by value, which includes two procedures: RefVal and MainCalc. The RefVal helper procedure uses three formal arguments, described in different ways. Further in the body of this procedure, each of them is increased by one, and then their values ​​are displayed on the screen. The main procedure, MainCalc, sets the values ​​of the variables a, b, and c, and then passes them as parameters to the RefVal procedure. In this case, the first parameter is passed by reference (by default), the second by value, and the third again by reference. After the RefVal procedure returns, the main procedure also displays the values ​​of the three variables passed as parameters. A total of six values ​​are displayed on the screen. First, these are the numbers 11, 21 and 31 (all obtained values ​​are increased by 1 and are output by the RefVal procedure). Then these are the numbers AND, 20 and 31 (these values ​​are output by the MainCalc procedure, with the variables passed by reference incremented, but the variable passed by value not).

Program 20.20. Difference between ByRef and ByVal

Sub RefVal(x, ByVal y, ByRef z)

MsgBox(z)End Sub

Sub MainCalc 0 a = 10 b = 20 s = 30 Call RefVal(a, b, c)

MsgBox(a) MsgBox(b) MsgBox(c) End Sub

So, we looked at working with user-defined procedures and functions, but in addition to this feature, there is a wide range of various built-in procedures and functions that allow the programmer not to think about implementing standard operations, such as comparing strings or taking the sine of a certain number. Unfortunately, the scope of our book does not allow us to describe even a small part of the built-in procedures and functions (and this is of no use), but you can always find their full list and description in the built-in Outlook help.



Copyright © 2024 Browsers. Antiviruses. Safety. Windows. Games. Video cards.