Articles

2: Functions


  • 2.1: Introduction to Functions
    Our development of the function concept is a modern one, but quite quick, particularly in light of the fact that today’s definition took over 300 years to reach its present state. We begin with the definition of a relation.
  • 2.2: The Graph of a Function
    Descartes introduces his coordinate system, a method for representing points in the plane via pairs of real numbers. Indeed, the Cartesian plane of modern day is so named in honor of Rene Descartes, who some call the “Father of Modern Mathematics.” A Cartesian Coordinate System consists of a pair of axes, usually drawn at right angles to one another in the plane, one horizontal (labeled x) and one vertical (labeled y).
  • 2.3: Interpreting the Graph of a Function
    In the previous section, we began with a function and then drew the graph of the given function. In this section, we will start with the graph of a function, then make a number of interpretations based on the given graph: function evaluations, the domain and range of the function, and solving equations and inequalities.
  • 2.4: Solving Equations and Inequalities by Graphing
    Our emphasis in the chapter has been on functions and the interpretation of their graphs. In this section, we continue in that vein and turn our exploration to the solution of equations and inequalities by graphing. The equations will have the form f(x)=g(x) , and the inequalities will have form f(x)g(x) .
  • 2.5: Vertical Transformations
    In this section we study the art of transformations: scalings, reflections, and translations. We will restrict our attention to transformations in the vertical or y-direction. Our goal is to apply certain transformations to the equation of a function, then ask what effect it has on the graph of the function.
  • 2.6: Horizontal Transformations
    In the previous section, we introduced the concept of transformations. We made a change to the basic equation y = f(x), such as y = af(x), y = −f(x), y = f(x) − c, or y = f(x) + c, then studied how these changes affected the shape of the graph of y = f(x). In that section, we concentrated strictly on transformations that applied in th vertical direction. In this section, we will study transformations that will affect the shape of the graph in the horizontal direction.
  • 2.7: Chapter 2 Exercises with Solutions

2: Functions

A function may also give back a value (like an output). For example the function max() (short for maximum) gives back the largest out of all of its arguments, which must be numbers.
The name return value means the value that a function gives back. For example in max(42, 17) we say that "the function max returned the value 42 ."

The max function has a friend which behaves similarly: the min function returns the minimum (smallest) of its arguments.

Functions can be combined to create more complicated expressions.

Your answer (enter a number):

You are not limited to using functions that are pre-defined in Python. In a few lessons you will learn how to define new functions!


Functions in C++

In this article, we will learn about Functions in C++.

A function is a segment of code that performs a certain task. A function in C++ is a set of statements with a name that can be called from anywhere in the program.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Why Functions in C++?

Let’s discuss answers to the questions like why do we need functions or why are functions so important. This is so because of the following reasons:

  • Readability: Functions bring modularity to our programs. They make programs more readable.
  • Control: Functions enable easy flow control amongst different parts of a program.
  • Redundancy: Functions reduce the redundancy of our programs. If we want a task to be done at multiple places in the program, we can call a function instead of writing the same code repeatedly.
  • Reusability: Functions increase the reusability of code.
  • Abstraction: Functions support abstraction. We can directly use functions from C++ library without knowing how a function works.
  • Error Handling: It becomes easier to find and debug errors.
  • Time: We can save a lot of time using functions.

Types of Functions in C++

1. Standard Library Functions: Functions predefined in C++ header files.

2. User-defined Functions: Functions defined by the user.

In this article, our focus will be on user-defined functions. We will learn how to define functions and use them in our program.

Defining a Function in C++

We can define a function following the syntax given below.

A function thus has the following parts:

  • return_type: it specifies the data type of the result that function will return.
  • function_name: it is the name given to a function.
  • parameters: it is the list of parameters the function is receiving. Here, we specify the number, type and order of parameters. A function may or may not have parameters.
    A function signature comprises function_name and parameters.
  • body: inside curly braces, we write statements to define the task of the function.

Example of a function definition in C++

  • The return type is void which means the function does not return any value
  • The function name is display
  • It does not have any parameter

Calling a Function in C++

We need to call or invoke a function wherever we want to use it.

Syntax to call a function with no (void) return type:

Syntax to call a function with a return type:

Here, ‘variable’ is the variable that will store the returned value. And argument1, argument2, … are the parameters that we pass to function.

Example of defining and calling a function in C++

Note that a C++ program always begins by calling the main function, regardless of the order in which functions are defined. In fact, main is the sole function that is called automatically, and code of other functions is run only if it is directly or indirectly called from main.

Function Parameters in C++

The parameters that we pass to a function during function call are called arguments or actual parameters. In the above example, n1 and n2 are actual parameters.

The local variables in the function definition are called formal parameters. In the above example, a and b are formal parameters.

When we call a function, actual parameters are assigned to formal parameters.

Function Declaration in C++

We can also give function definition after function call. But, in that case, it is necessary to declare the function beforehand. It is also called function prototype.

Example of Function Declaration in C++

Observe that we obtain the same output in both ways.

Passing Arguments in C++

While calling a function, we can pass arguments in three ways.

1. Call by value

In call by value (or pass by value), values of arguments are passed which are copied to the formal parameters. Actual parameters and formal parameters are stored in different locations of memory. Hence, modifications done to the formal parameters inside the function are not reflected in the actual parameters outside it.

2. Call by reference

In call by reference (or pass by reference), references of arguments get copied to the formal parameters. Using these references, the actual parameters are accessed from inside the function. Thus, modifications done inside the function get reflected in the actual parameters outside it.

3. Call by Pointer

In call by pointer (or pass by pointer), we pass addresses of variables. Hence, both actual and formal parameters point to the same location. Thus, modifications done to the formal parameters inside the function get reflected in the actual parameters outside it.

Let’s understand with examples:

Example of call by value in C++

#include <iostream> using namespace std void modify(int a) < a+=2 >int main() < int x = 3 modify(x) cout<<"x code-output">x = 3

Observe that in this case, the value of x remains unchanged.

Example of call by reference in C++

#include <iostream> using namespace std void modify(int &a) < a+=2 >int main() < int x = 3 modify(x) cout<<"x code-output">x = 5

Now, the value of x has changed.

Example of call by pointer in C++

In this case also the value of x changes.

Summary

We covered functions in this article. We learnt how to define and declare a function in C++. You must have observed that every function has a return type. Then, we learnt how to call a function. We also noted the importance of the main function in C++. Finally, we learnt about call by value, call by reference and call by pointer methods of passing arguments to a function. We provided suitable examples for better understanding of the concepts.


Migrate from 1.x to 2.x

This section describes how to migrate your existing version 1.x Durable Functions to version 2.x to take advantage of the new features.

Upgrade the extension

Install the latest 2.x version of the Durable Functions bindings extension in your project.

JavaScript, Python, and PowerShell

Durable Functions 2.x is available in version 2.x of the Azure Functions extension bundle.

Python support in Durable Functions requires Durable Functions 2.x.

To update the extension bundle version in your project, open host.json and update the extensionBundle section to use version 2.x ( [2.*, 3.0.0) ).

If Visual Studio Code is not displaying the correct templates after you change the extension bundle version, reload the window by running the Developer: Reload Window command ( Ctrl+R on Windows and Linux, Command+R on macOS).

Update your .NET project to use the latest version of the Durable Functions bindings extension.

Update your code

Durable Functions 2.x introduces several breaking changes. Durable Functions 1.x applications are not compatible with Durable Functions 2.x without code changes. This section lists some of the changes you must make when upgrading your version 1.x functions to 2.x.

Host.json schema

Durable Functions 2.x uses a new host.json schema. The main changes from 1.x include:

  • "storageProvider" (and the "azureStorage" subsection) for storage-specific configuration.
  • "tracing" for tracing and logging configuration.
  • "notifications" (and the "eventGrid" subsection) for event grid notification configuration.

Default taskhub name changes

In version 1.x, if a task hub name was not specified in host.json, it was defaulted to "DurableFunctionsHub". In version 2.x, the default task hub name is now derived from the name of the function app. Because of this, if you have not specified a task hub name when upgrading to 2.x, your code will be operating with new task hub, and all in-flight orchestrations will no longer have an application processing them. To work around this, you can either explicitly set your task hub name to the v1.x default of "DurableFunctionsHub", or you can follow our zero-downtime deployment guidance for details on how to handle breaking changes for in-flight orchestrations.

Public interface changes (.NET only)

In version 1.x, the various context objects supported by Durable Functions have abstract base classes intended for use in unit testing. As part of Durable Functions 2.x, these abstract base classes are replaced with interfaces.

The following table represents the main changes:

1.x 2.x
DurableOrchestrationClientBase IDurableOrchestrationClient or IDurableClient
DurableOrchestrationContext or DurableOrchestrationContextBase IDurableOrchestrationContext
DurableActivityContext or DurableActivityContextBase IDurableActivityContext
OrchestrationClientAttribute DurableClientAttribute

In the case where an abstract base class contained virtual methods, these virtual methods have been replaced by extension methods defined in DurableContextExtensions .

Function.json changes (JavaScript and C# Script)

In Durable Functions 1.x, the orchestration client binding uses a type of orchestrationClient . Version 2.x uses durableClient instead.

Raise event changes

In Durable Functions 1.x, calling the raise event API and specifying an instance that did not exist resulted in a silent failure. Starting in 2.x, raising an event to a non-existent orchestration results in an exception.


What to know about vitamin K-2

Vitamin K is an essential vitamin that supports blood clotting and healthy bones. It occurs in two forms, K-1 and K-2.

Vitamin K-1 is the primary form, and it mainly comes from leafy green vegetables. Vitamin K-2 occurs in animal proteins and fermented foods. The bacteria in the human gut also produce small quantities of K-2.

In this article, we discuss vitamin K-2, its functions, and how it differs from K-1. We also describe dietary sources, health benefits, the recommended daily intake, deficiency symptoms, and supplements.

Share on Pinterest Sauerkraut is a good dietary source of vitamin K-2.

Vitamin K refers to a family of fat-soluble vitamins that the body needs to produce a protein called prothrombin, which promotes blood clotting and regulates bone metabolism.

The vitamin comes in two main forms:

  • Vitamin K-1, or phylloquinone, occurs naturally in dark leafy green vegetables and is the main dietary source of vitamin K.
  • Vitamin K-2, or menaquinone, is present in small quantities in organ meats and fermented foods. Gut bacteria also produce vitamin K-2.

The body needs both types of vitamin K to produce prothrombin, a protein that plays crucial roles in blood clotting, bone metabolism, and heart health. Vitamin K also helps facilitate energy production in the mitochondria of cells.

Vitamin K-1 is primarily involved in blood coagulation. K-2 may have a more diverse range of functions in the body.

In a long-term study involving 36,629 participants, researchers observed an association

between high intakes of vitamin K-2 and a reduced risk of developing peripheral arterial disease (PAD), particularly in people with high blood pressure. However, the authors concluded that K-1 had no effect on PAD risk.

Vitamin K has antioxidant properties. It protects cellular membranes from damage due to excess free radicals, in a process known as peroxidation. Blood thinning medication, such as warfarin, can lower the antioxidative potential of vitamin K.

Vitamins K-1 and K-2 have different chemical structures. Both types have a phytyl side chain, but K-2 also has isoprenoid side chains.

K-2 has several subtypes, called menaquinones (MKs), which scientists have numbered MK-4 through MK-13, based on the length of their side chains.

K-1 is the primary form of the vitamin, and it is mainly present in leafy green vegetables. However, the body has difficulty absorbing vitamin K-1 from plants.

According to a 2019 review , research suggests that the body absorbs 10 times more vitamin K-2, in the form of MK-7, than vitamin K-1.

Vitamin K is fat-soluble, so eating dietary fats, such as butter or plant oils, may enhance the body’s absorption of vitamin K-1 from plants.

Bacteria in the gut can synthesize vitamin K-1 into vitamin K-2. Also, fermented foods, meat, and dairy products contain modest amounts of vitamin K-2.

The body stores vitamins K-1 and K-2 differently. K-1 accumulates in the liver, heart, and pancreas. K-2 occurs in high concentrations in the brain and kidneys.

Several foods are rich in vitamin K-1, and vitamin K-2 is much less common. Bacteria in the gut can convert some K-1 into K-2.

Fermented foods are a good source of vitamin K-2.

Also, because it is fat-soluble, organ meats and high-fat dairy products contain fairly substantial quantities of vitamin K-2. Conversely, lean meats, such as poultry, are not good sources of K-2.

Dietary sources of vitamin K-1 include:

  • dark leafy green vegetables, such as spinach, kale, and collards
  • lettuce
  • turnips
  • broccoli
  • carrots
  • vegetable oils
  • grapes

Dietary sources of vitamin K-2 include:

  • natto, a traditional Japanese dish of fermented soybeans
  • sauerkraut
  • dairy products, especially hard cheeses
  • liver and other organ meats
  • beef
  • pork
  • egg yolks
  • chicken
  • fatty fish, such as salmon

In addition to its crucial role in blood clotting and wound healing, vitamin K-2 has a number of other health benefits. We discuss some of these below.

Heart health

Vitamin K-2 may lower the risk of cardiovascular damage and improve overall heart health.

According to a 2015 review article , K-2 activates a protein that prevents calcium deposits from forming in the walls of blood vessels. The author cited findings suggesting that a diet high in natural vitamin K2 may decrease the risk of coronary heart disease.

Bone health

Vitamin K-2 promotes healthy bone mineral density by carboxylating osteocalcin, a protein that binds calcium to bones.

A 2019 study investigated the effects of taking MK-4 supplements in 29 postmenopausal females who had experienced hip or vertebral compression fractures.

The researchers concluded that taking 5 milligrams of an MK-4 supplement daily reduced the levels of undercarboxylated osteocalcin to that “typical of healthy, premenopausal women.”

A 2017 study from Japan examined whether vitamin K-2 enhances the effects of standard medication for osteoporosis in adult females aged 65 or older. According to the results, vitamin K-2 did not appear to enhance the effects of the osteoporosis medication.

Anxiety and depression

High blood glucose levels may increase a person’s risk of developing depression, anxiety, and cognitive impairment.

A 2016 study investigated the effects of vitamin K-2 in rats with metabolic syndrome, high blood glucose levels and symptoms of anxiety, depression, and memory deficit.

After 10 weeks, treatment with vitamin K had normalized blood glucose and reduced symptoms of anxiety and depression. However, it did not improve memory deficit in the rats.

Cancer

Vitamin K-2 has antioxidant properties that may help protect against cancer. In addition, findings suggest that K-2 may suppress genetic processes that lead to tumor growth.

According to a 2018 study, vitamin K-2 that scientists had modified with a sialic acid-cholesterol conjugate significantly suppressed tumor growth in mouse cells.

A 2019 study suggests that K-2 significantly reduces the activity of hypoxia-inducible factor 1-alpha (HIF-1A) in hepatocellular carcinoma cells. HIF-1A is an important target for cancer drug therapy.


2: Functions

Spark also includes more built-in functions that are less common and are not defined here. You can still access them (and all the functions defined here) using the functions.expr() API and calling them through a SQL expression string. You can find the entire list of functions at SQL API documentation.

As an example, isnan is a function that is defined here. You can use isnan(col("myCol")) to invoke the isnan function. This way the programming language's compiler ensures isnan exists and is of the proper form. You can also use expr("isnan(myCol)") function to invoke the same function. In this case, Spark itself will ensure isnan exists when it analyzes the query.

regr_count is an example of a function that is built-in but not defined here, because it is less commonly used. To invoke it, use expr("regr_count(yCol, xCol)") .

This function APIs usually have methods with Column signature only because it can support not only Column but also other types such as a native string. The other variants currently exist for historical reasons.


Block-level functions

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

Block-level functions in non-strict code

In non-strict code, function declarations inside blocks behave strangely. For example:

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if -block.

A safer way to define functions conditionally is to assign a function expression to a variable:


2: Functions

Operations on Functions

In this section we will learn what it means to add, subtract, multiply, and divide two functions. Learning these operations is important because almost any function you encounter is the sum, difference, product, or quotient (or any combination of these operations) of simpler functions. You will also learn to find the domain and range of these functions.

The Sum of Two Functions

Suppose we have two functions, f(x) and g(x). We can define the sum of these two functions by,

where x is in the domain of both f and g.

For example, we can add the functions f(x) = x 2 &minus 1 and g(x) = 2x 3 + 3 as,

The domain of (f + g)(x) consists of all x-values that are in the domain of both f and g. In this example, f and g both have domain consisting of all real numbers, therefore (f + g)(x) also has domain consisting of all real numbers.

The Difference of Two Functions

Suppose we have two functions, f(x) and g(x). We can define the difference of these two functions by,

where x is in the domain of both f and g.

The domain of the (f &minus g)(x) consists of all x-values that are in the domain of both f and g. In this case, f has domain , and g has domain all real numbers, therefore (f &minus g)(x) has domain , because these values of x are in the domain of both f and g.

The Product of Two Functions

Suppose we have two functions, f(x) and g(x). We can define the product of these two functions by,

where x is in the domain of both f and g.

For example, we can multiply the functions f(x) = 1/ x and g(x) = 2 as,

The domain of the (f ·g)(x) consists of all x-values that are in the domain of both f and g. In this example, f has domain <x | x &ne 0>, and g has domain all real numbers, therefore (f · g)(x) has domain <x | x &ne 0>, because these values of x are in the domain of both f and g.

The Quotient of Two Functions

Suppose we have two functions, f(x) and g(x). We can define the quotient of these two functions by,

where x is in the domain of both f and g. It is important to specifyg(x) &ne 0 because we cannot divide by zero. For example, we can divide the functions f(x) = x &minus 7 and g(x) = x + 5 as,

The domain of (f/g) (x) consists of all x-values that are in the domain of both f and g, where g(x) &ne 0. Both f and g have domain all real numbers, but g(x) = 0 when x = &minus5. Thus, the domain of (f/g) (x) is <x | x &ne &minus5>.

In the next section we learn how to take the composition of two functions.


Functions

Functions allow to structure programs in segments of code to perform individual tasks.

In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:

type name ( parameter1, parameter2, . ) < statements >

Where:
- type is the type of the value returned by the function.
- name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x ), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces < >that specify what the function actually does.

Let's have a look at an example:

This program is divided in two functions: addition and main . Remember that no matter the order in which they are defined, a C++ program always starts by calling main . In fact, main is the only function called automatically, and the code in any other function is only executed if its function is called from main (directly or indirectly).

In the example above, main begins by declaring the variable z of type int , and right after that, it performs the first function call: it calls addition . The call to a function follows a structure very similar to its declaration. In the example above, the call to addition can be compared to its definition just a few lines earlier:


The parameters in the function declaration have a clear correspondence to the arguments passed in the function call. The call passes two values, 5 and 3 , to the function these correspond to the parameters a and b , declared for function addition .

At the point at which the function is called from within main, the control is passed to function addition : here, execution of main is stopped, and will only resume once the addition function ends. At the moment of the function call, the value of both arguments ( 5 and 3 ) are copied to the local variables int a and int b within the function.

Then, inside addition , another local variable is declared ( int r ), and by means of the expression r=a+b , the result of a plus b is assigned to r which, for this case, where a is 5 and b is 3, means that 8 is assigned to r .

The final statement within the function:

Ends function addition , and returns the control back to the point where the function was called in this case: to function main . At this precise moment, the program resumes its course on main returning exactly at the same point at which it was interrupted by the call to addition . But additionally, because addition has a return type, the call is evaluated as having a value, and this value is the value specified in the return statement that ended addition : in this particular case, the value of the local variable r , which at the moment of the return statement had a value of 8.


Therefore, the call to addition is an expression with the value returned by the function, and in this case, that value, 8, is assigned to z . It is as if the entire function call ( addition(5,3) ) was replaced by the value it returns (i.e., 8).

Then main simply prints this value by calling:

A function can actually be called multiple times within a program, and its argument is naturally not limited just to literals:

Similar to the addition function in the previous example, this example defines a subtract function, that simply returns the difference between its two parameters. This time, main calls this function several times, demonstrating more possible ways in which a function can be called.

Let's examine each of these calls, bearing in mind that each function call is itself an expression that is evaluated as the value it returns. Again, you can think of it as if the function call was itself replaced by the returned value:

If we replace the function call by the value it returns (i.e., 5), we would have:

With the same procedure, we could interpret:

since 5 is the value returned by subtraction (7,2) .

The arguments passed to subtraction are variables instead of literals. That is also valid, and works fine. The function is called with the values x and y have at the moment of the call: 5 and 3 respectively, returning 2 as result.

The fourth call is again similar:

The only addition being that now the function call is also an operand of an addition operation. Again, the result is the same as if the function call was replaced by its result: 6. Note, that thanks to the commutative property of additions, the above can also be written as:

With exactly the same result. Note also that the semicolon does not necessarily go after the function call, but, as always, at the end of the whole statement. Again, the logic behind may be easily seen again by replacing the function calls by their returned value:

Functions with no type. The use of void

The syntax shown above for functions:

type name ( argument1, argument2 . ) < statements >

Requires the declaration to begin with a type. This is the type of the value returned by the function. But what if the function does not need to return a value? In this case, the type to be used is void , which is a special type to represent the absence of value. For example, a function that simply prints a message may not need to return any value:

void can also be used in the function's parameter list to explicitly specify that the function takes no actual parameters when called. For example, printmessage could have been declared as:

In C++, an empty parameter list can be used instead of void with same meaning, but the use of void in the argument list was popularized by the C language, where this is a requirement.

Something that in no case is optional are the parentheses that follow the function name, neither in its declaration nor when calling it. And even when the function takes no parameters, at least an empty pair of parentheses shall always be appended to the function name. See how printmessage was called in an earlier example:

The parentheses are what differentiate functions from other kinds of declarations or statements. The following would not call the function:

The return value of main

You may have noticed that the return type of main is int , but most examples in this and earlier chapters did not actually return any value from main .

Well, there is a catch: If the execution of main ends normally without encountering a return statement the compiler assumes the function ends with an implicit return statement:

Note that this only applies to function main for historical reasons. All other functions with a return type shall end with a proper return statement that includes a return value, even if this is never used.

When main returns zero (either implicitly or explicitly), it is interpreted by the environment as that the program ended successfully. Other values may be returned by main , and some environments give access to that value to the caller in some way, although this behavior is not required nor necessarily portable between platforms. The values for main that are guaranteed to be interpreted in the same way on all platforms are:

valuedescription
0 The program was successful
EXIT_SUCCESS The program was successful (same as above).
This value is defined in header <cstdlib> .
EXIT_FAILURE The program failed.
This value is defined in header <cstdlib> .

Because the implicit return 0 statement for main is a tricky exception, some authors consider it good practice to explicitly write the statement.

Arguments passed by value and by reference

In the functions seen earlier, arguments have always been passed by value. This means that, when calling a function, what is passed to the function are the values of these arguments on the moment of the call, which are copied into the variables represented by the function parameters. For example, take:

In this case, function addition is passed 5 and 3, which are copies of the values of x and y , respectively. These values (5 and 3) are used to initialize the variables set as parameters in the function's definition, but any modification of these variables within the function has no effect on the values of the variables x and y outside it, because x and y were themselves not passed to the function on the call, but only copies of their values at that moment.


In certain cases, though, it may be useful to access an external variable from within a function. To do that, arguments can be passed by reference, instead of by value. For example, the function duplicate in this code duplicates the value of its three arguments, causing the variables used as arguments to actually be modified by the call:

To gain access to its arguments, the function declares its parameters as references. In C++, references are indicated with an ampersand ( & ) following the parameter type, as in the parameters taken by duplicate in the example above.

When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to the function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call.

In fact, a , b , and c become aliases of the arguments passed on the function call ( x , y , and z ) and any change on a within the function is actually modifying variable x outside the function. Any change on b modifies y , and any change on c modifies z . That is why when, in the example, function duplicate modifies the values of variables a , b , and c , the values of x , y , and z are affected.

If instead of defining duplicate as:

Was it to be defined without the ampersand signs as:

The variables would not be passed by reference, but by value, creating instead copies of their values. In this case, the output of the program would have been the values of x , y , and z without being modified (i.e., 1, 3, and 7).

Efficiency considerations and const references

Calling a function with parameters taken by value causes copies of the values to be made. This is a relatively inexpensive operation for fundamental types such as int , but if the parameter is of a large compound type, it may result on certain overhead. For example, consider the following function:

This function takes two strings as parameters (by value), and returns the result of concatenating them. By passing the arguments by value, the function forces a and b to be copies of the arguments passed to the function when it is called. And if these are long strings, it may mean copying large quantities of data just for the function call.

But this copy can be avoided altogether if both parameters are made references:

Arguments by reference do not require a copy. The function operates directly on (aliases of) the strings passed as arguments, and, at most, it might mean the transfer of certain pointers to the function. In this regard, the version of concatenate taking references is more efficient than the version taking values, since it does not need to copy expensive-to-copy strings.

On the flip side, functions with reference parameters are generally perceived as functions that modify the arguments passed, because that is why reference parameters are actually for.

The solution is for the function to guarantee that its reference parameters are not going to be modified by this function. This can be done by qualifying the parameters as constant:

By qualifying them as const , the function is forbidden to modify the values of neither a nor b , but can actually access their values as references (aliases of the arguments), without having to make actual copies of the strings.

Therefore, const references provide functionality similar to passing arguments by value, but with an increased efficiency for parameters of large types. That is why they are extremely popular in C++ for arguments of compound types. Note though, that for most fundamental types, there is no noticeable difference in efficiency, and in some cases, const references may even be less efficient!

Inline functions

Calling a function generally causes a certain overhead (stacking arguments, jumps, etc. ), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.

Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.

For example, the concatenate function above may be declared inline as:

This informs the compiler that when concatenate is called, the program prefers the function to be expanded inline, instead of performing a regular call. inline is only specified in the function declaration, not when it is called.

Note that most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise. In C++, optimization is a task delegated to the compiler, which is free to generate any code for as long as the resulting behavior is the one specified by the code.

Default values in parameters

In C++, functions can also have optional parameters, for which no arguments are required in the call, in such a way that, for example, a function with three parameters may be called with only two. For this, the function shall include a default value for its last parameter, which is used by the function when called with fewer arguments. For example:

In this example, there are two calls to function divide . In the first one:

The call only passes one argument to the function, even though the function has two parameters. In this case, the function assumes the second parameter to be 2 (notice the function definition, which declares its second parameter as int b=2 ). Therefore, the result is 6.

The call passes two arguments to the function. Therefore, the default value for b ( int b=2 ) is ignored, and b takes the value passed as argument, that is 4, yielding a result of 5.

Declaring functions

In C++, identifiers can only be used in expressions once they have been declared. For example, some variable x cannot be used before being declared with a statement, such as:

The same applies to functions. Functions cannot be called before they are declared. That is why, in all the previous examples of functions, the functions were always defined before the main function, which is the function from where the other functions were called. If main were defined before the other functions, this would break the rule that functions shall be declared before being used, and thus would not compile.

The prototype of a function can be declared without actually defining the function completely, giving just enough details to allow the types involved in a function call to be known. Naturally, the function shall be defined somewhere else, like later in the code. But at least, once declared like this, it can already be called.

The declaration shall include all types involved (the return type and the type of its arguments), using the same syntax as used in the definition of the function, but replacing the body of the function (the block of statements) with an ending semicolon.

The parameter list does not need to include the parameter names, but only their types. Parameter names can nevertheless be specified, but they are optional, and do not need to necessarily match those in the function definition. For example, a function called protofunction with two int parameters can be declared with either of these statements:

Anyway, including a name for each parameter always improves legibility of the declaration.

This example is indeed not an example of efficiency. You can probably write yourself a version of this program with half the lines of code. Anyway, this example illustrates how functions can be declared before its definition:

Declare the prototype of the functions. They already contain all what is necessary to call them, their name, the types of their argument, and their return type ( void in this case). With these prototype declarations in place, they can be called before they are entirely defined, allowing for example, to place the function from where they are called ( main ) before the actual definition of these functions.

But declaring functions before being defined is not only useful to reorganize the order of functions within the code. In some cases, such as in this particular case, at least one of the declarations is required, because odd and even are mutually called there is a call to even in odd and a call to odd in even . And, therefore, there is no way to structure the code so that odd is defined before even , and even before odd .

Recursivity

Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number ( n! ) the mathematical formula would be:

n! = n * (n-1) * (n-2) * (n-3) . * 1
More concretely, 5! (factorial of 5) would be:

5! = 5 * 4 * 3 * 2 * 1 = 120
And a recursive function to calculate this in C++ could be:


Functions of Management

Management has been described as a social process involving responsibility for economical and effective planning & regulation of operation of an enterprise in the fulfillment of given purposes. It is a dynamic process consisting of various elements and activities. These activities are different from operative functions like marketing, finance, purchase etc. Rather these activities are common to each and every manger irrespective of his level or status.

Different experts have classified functions of management. According to George & Jerry, “There are four fundamental functions of management i.e. planning, organizing, actuating and controlling”.

According to Henry Fayol, “To manage is to forecast and plan, to organize, to command, & to control”. Whereas Luther Gullick has given a keyword ’POSDCORB’ where P stands for Planning, O for Organizing, S for Staffing, D for Directing, Co for Co-ordination, R for reporting & B for Budgeting. But the most widely accepted are functions of management given by KOONTZ and O’DONNEL i.e. Planning, Organizing, Staffing, Directing and Controlling.

For theoretical purposes, it may be convenient to separate the function of management but practically these functions are overlapping in nature i.e. they are highly inseparable. Each function blends into the other & each affects the performance of others.

Planning

It is the basic function of management. It deals with chalking out a future course of action & deciding in advance the most appropriate course of actions for achievement of pre-determined goals. According to KOONTZ, “Planning is deciding in advance - what to do, when to do & how to do. It bridges the gap from where we are & where we want to be”. A plan is a future course of actions. It is an exercise in problem solving & decision making. Planning is determination of courses of action to achieve desired goals. Thus, planning is a systematic thinking about ways & means for accomplishment of pre-determined goals. Planning is necessary to ensure proper utilization of human & non-human resources. It is all pervasive, it is an intellectual activity and it also helps in avoiding confusion, uncertainties, risks, wastages etc.

Organizing

It is the process of bringing together physical, financial and human resources and developing productive relationship amongst them for achievement of organizational goals. According to Henry Fayol, “To organize a business is to provide it with everything useful or its functioning i.e. raw material, tools, capital and personnel’s”. To organize a business involves determining & providing human and non-human resources to the organizational structure. Organizing as a process involves:

  • Identification of activities.
  • Classification of grouping of activities.
  • Assignment of duties.
  • Delegation of authority and creation of responsibility.
  • Coordinating authority and responsibility relationships.

Staffing

It is the function of manning the organization structure and keeping it manned. Staffing has assumed greater importance in the recent years due to advancement of technology, increase in size of business, complexity of human behavior etc. The main purpose o staffing is to put right man on right job i.e. square pegs in square holes and round pegs in round holes. According to Kootz & O’Donell, “Managerial function of staffing involves manning the organization structure through proper and effective selection, appraisal & development of personnel to fill the roles designed un the structure”. Staffing involves:

    (estimating man power in terms of searching, choose the person and giving the right place).
  • Recruitment, Selection & Placement. . . .
  • Promotions & Transfer.

Directing

It is that part of managerial function which actuates the organizational methods to work efficiently for achievement of organizational purposes. It is considered life-spark of the enterprise which sets it in motion the action of people because planning, organizing and staffing are the mere preparations for doing the work. Direction is that inert-personnel aspect of management which deals directly with influencing, guiding, supervising, motivating sub-ordinate for the achievement of organizational goals. Direction has following elements:

Supervision- implies overseeing the work of subordinates by their superiors. It is the act of watching & directing work & workers.

Motivation- means inspiring, stimulating or encouraging the sub-ordinates with zeal to work. Positive, negative, monetary, non-monetary incentives may be used for this purpose.

Leadership- may be defined as a process by which manager guides and influences the work of subordinates in desired direction.

Communications- is the process of passing information, experience, opinion etc from one person to another. It is a bridge of understanding.

Controlling

It implies measurement of accomplishment against the standards and correction of deviation if any to ensure achievement of organizational goals. The purpose of controlling is to ensure that everything occurs in conformities with the standards. An efficient system of control helps to predict deviations before they actually occur. According to Theo Haimann, “Controlling is the process of checking whether or not proper progress is being made towards the objectives and goals and acting if necessary, to correct any deviation”. According to Koontz & O’Donell “Controlling is the measurement & correction of performance activities of subordinates in order to make sure that the enterprise objectives and plans desired to obtain them as being accomplished”. Therefore controlling has following steps:

  1. Establishment of standard performance.
  2. Measurement of actual performance.
  3. Comparison of actual performance with the standards and finding out deviation if any.
  4. Corrective action.

Learn management concepts & skills rapidly with easy to understand, richly illustrated self-paced learning modules & downloadable powerpoint presentations.

Download DEMO Presentation Now!.

As a premium member, you get access to view complete course content online and download powerpoint presentations for more than 200 courses in management and skills area.


Watch the video: Sega Genesis Classics Nintendo Switch Gameplay (October 2021).