Function Definition

mikroC Pro for PIC Programming Language

Dogan Ibrahim , in PIC Microcontroller Projects in C (Second Edition), 2014

2.7 mikroC Pro for PIC Functions

An example function definition is shown below. This function, named Mult, receives two integer arguments a and b and returns their product. Notice that using brackets in a return statement are optional:

int Mult(int a, int b)

  {

      return (ab);

  }

When a function is called, it generally expects to be given the number of arguments expressed in the function's argument list. For example, the above function can be called as

  z   =   Mult(x,y);

Where variable z has the data type int. In the above example, when the function is called, variable x is copied to a, and variable y is copied to b on entry to function Mult.

Some functions do not return any data and the data type of such functions must be declared as void. An example is given below:

void LED(unsigned char D)

  {

      PORTB   =   D;

  }

void functions can be called without any assignment statements, but the brackets must be used to tell the compiler that a function call is made.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780080999241000022

MATLAB Programs

Stormy Attaway , in MATLAB (Fifth Edition), 2019

6.1.2 Functions That Accomplish a Task Without Returning Values

Many functions do not calculate values, but rather accomplish a task, such as printing formatted output. As these functions do not return any values, there are no output arguments in the function header.

The general form of a function definition for a function that does not return any values looks like this:

functionname.m

function functionname(input arguments)

% Comment describing the function

Statements here

end

Note

What is missing in the function header: there are no output arguments and no assignment operator.

For example, the following function just prints the two arguments, numbers, passed to it in a sentence format:

printem.m

function printem(a,b)

% printem prints two numbers in a sentence format

% Format: printem(num1, num2)

fprintf('The first number is %.1f and the second is %.1f\n',a,b)

end

As this function performs no calculations, there are no output arguments in the function header and no assignment operator (=). An example of a call to the printem function is:

>> printem(3.3, 2)

The first number is 3.3 and the second is 2.0

Note that as the function does not return a value, it cannot be called from an assignment statement. Any attempt to do this would result in an error, such as the following:

>> x = printem(3, 5)   % Error!!

Error using printem

Too many output arguments.

We can therefore think of the call to a function that does not return values as a statement by itself, in that the function call cannot be imbedded in another statement such as an assignment statement or an output statement.

The tasks that are accomplished by functions that do not return any values (e.g., output from an fprintf statement or a plot) are sometimes referred to as side effects . Some standards for commenting functions include putting the side effects in the block comment.

Practice 6.2

Write a function that receives a vector as an input argument and prints the individual elements from the vector in a sentence format.

>> printvecelems([5.9   33   11])

Element 1 is 5.9

Element 2 is 33.0

Element 3 is 11.0

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000064

Software Fault Prevention by Language Choice: Why C is Not My Favorite Language

Richard Fateman , in Advances in Computers, 2002

4.2 Interface Flaws

This class of flaws consists of apparent disagreements between function definitions and their uses. The caller assumes an argument is a pointer, but the function disagrees. A consequence of some such disagreements can be that an erroneously passed copy of a large structure may overflow a stack. Many of these errors would not occur in Lisp, although there is still the possibility of using arguments in the wrong order, or simply calling the wrong function. Rather than insisting that functions with no return values be declared of return type void, it has been historically convenient in Lisp to decide that every function returns a value; if nothing else comes to mind, perhaps a condition code. Common Lisp allows multiple returned values (any number including 0 values), which removes the necessity for "in/out" or "output parameters" in argument lists. We discuss this "functional" orientation again when we provide arguments against Lisp, but for now, let us say that Lisp allows interfaces that are rather more versatile, allowing optional, keyword, and default arguments. Argument-count checking can be done at compile time and also enforced at runtime.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/S0065245802800067

Recent Developments and Applications of Modern Density Functional Theory

N.H. March , in Theoretical and Computational Chemistry, 1996

5.2 Relation between correlation energy Ec [ρ] and density-functional definition of kinetic contribution Tc [ρ]

It is useful to summarize here the density-function definition of the kinetic contribution Tc [ρ] to the correlation energy Ec [ρ]. Here

(48) E c ρ = Ψ ρ 1 | T ^ + V ^ e e | Ψ ρ 1 Ψ ρ 0 | T ^ + V ^ e e | Ψ ρ 0

and

(49) T c ρ = Ψ ρ 1 | T ^ | Ψ ρ 1 Ψ ρ 0 | T ^ | Ψ ρ 0 .

It is expected [16], with these definitions, that Ec [ρ]     Tc [ρ]. However, there is an exact relation connecting Ec [ρ] and Tc [ρ], namely [33]

(50) E c ρ = T c ρ + E c ρ λ λ λ = 1 .

Hence it follows that a necessary and sufficient condition for the two-point formula to be exact, when the exact U λ xc is used in Eq. (41), is

(51) E c ρ λ λ λ = 1 = 0 .

Levy et al [16] note, in support of the two-point formula, that the magnitude of E c ρ λ λ λ = 1 has been found to be typically only about 10% of the magnitude of Ec [ρ] in atoms.

Having discussed E[ρ] at some length, we return to treat the generalization of the Thomas-Fermi force equation (5).

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/S1380732396800859

C and the embedded environment

Tim Wilmshurst , in Designing Embedded Systems with PIC Microcontrollers (Second Edition), 2010

15.3.2 The function definition

The actual code of a function is called the 'function definition'. It follows the format described in Section 14.2.5 of Chapter 14. The definition for the Delay10KTCYx( ) function is contained within the general software library (Table 14.5) and is merged with the main program at the time of linking.

The definitions for the two user-defined functions can be seen towards the end of the program listing. They are placed here for clarity. They can, however, be placed anywhere in the program listing, as long as they are not inside another function definition. These definitions are easy to follow.

The initialise function sets up the SFRs and initialises the ports to 0. Strictly speaking, initialising variables to 0 should be unnecessary as the ANSI standard requires it anyway. With C18 this is only done if the c018iz.o start-up utility is used (described later, in Section 17.7.1 of Chapter 17). We do not use this in the example programs in this book and variables are hence not initialised to zero as a matter of course. The diagnostic function sets bits 5 and 6 of Port C (the two LED output bits) to 1 and calls the delay function. It then clears the same bits to zero, before calling the same delay again.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9781856177504100198

Artificial Intelligence Programming

Günter Neumann , in Encyclopedia of Information Systems, 2003

III.E. Recursive Function Definitions

The second central device for defining control flow in Lisp is recursive function definitions . A function which partially uses its definition as part of its own definition is called recursive. Thus seen, a recursive definition is one in which a problem is decomposed into smaller units until no further decomposition is possible. Then these smaller units are solved using known function definitions, and the sum of the corresponding solutions form the solution of the complete program. Recursion is a natural control regime for data structures which have no definite size, such as lists, trees, and graphs. Therefore, it is particularly appropriate for problems in which a space of states has to be searched for candidate solutions.

Lisp was the first practical programming language that systematically supported the definition of recursive definitions. We will use two small examples to demonstrate recursion in Lisp. The first example is used to determine the length of an arbitrarily long list. The length of a list corresponds to the number of its elements. Its recursive function is as follows:

When defining a recursive definition, we have to identify the base cases, i.e., those units which cannot be decomposed any further. Our problem size is the list. The smallest problem size of a list is the empty list. Thus, the first thing we have to do is to specify is a test for identifying the empty list and to define what the length of the empty list should be. The built-in function NULL tests whether a list is empty, in which case it returns T. Since the empty list is a list with no elements, we define the length of the empty list as 0. The next thing to be done is to decompose the problem size into smaller units so that the same problem can be applied to smaller units. Decomposition of a list can be done by using the functions CAR and CDR, which means that we have to specify what is to be done with the first element of a list and the rest until the empty list is found. Since we already have identified the empty list as the base case, we can assume that decomposition will be performed on a list containing at least one element. Thus, every time we are able to apply CDR to get the rest of a list, we have found one additional element which should be used to increase the number of the already identified list elements by 1. Making use of this function definition, (LENGTH '()) will immediately return 0, and if we call (LENGTH()) '(A B C)), the result will be 3, because three recursive calls have to be performed until the empty list can be determined.

As a second example, we consider the recursive definition of MEMBER, a function which tests whether a given element occurs in a given list. If the element is indeed found in the list, it returns the sublist which starts with the first occurrence of the found element. If the element cannot be found, NIL is returned. The following are example calls:

Similarly to the recursive definition of LENGTH, we use the empty list as the base case. For MEMBER, the empty list means that the element in question is not found in the list. Thus, we have to decompose a list until the element in question is found or the empty list is determined. Decomposition is done using CAR and CDR. CAR is used to extract the first element of a list, which can be used to check whether it is equal to the element in question, in which case we can directly stop further processing. If it is not equal, then we should apply the MEMBER function on the remaining elements until the empty list is determined. Thus, MEMBER can be defined as follows:

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B0122272404000034

Architecture Approach

Charles T. Betz , in Architecture and Patterns for IT Service Management, Resource Planning, and Governance: Making Shoes for the Cobbler's Children (Second Edition), 2011

IT Function Summary Definitions

See Appendix A for detailed definitions of each function.

Table 2-7. IT Function Definitions

Planning, Governance, and Support Capabilities Overall coordination and control of the IT capability. Necessary tie-breaker between application and infrastructure perspectives.
Strategy, Architecture, and Portfolio Management Planning, design and standards authority, consulting arm, business intelligence for the business of IT.
IT Resource Management Sourcing, control, and coordination of all tangible IT resources including money, assets, and personnel.
IT Financial Management Control the financial resource used in delivery of IT services.
IT Sourcing, Supply Chain, and Asset Management Establish sourcing and supply chain principles and tracks IT assets. Own the IT Asset lifecycle.
IT Human Resource Management Control the human resource used in the delivery of IT services.
Risk, Security, and Compliance Manage and assess critical control objectives ensuring service integrity, data protection, effective delivery, and adherence to laws.
Security Management Protect systems from unauthorized access (internal and external). Defines protocols and ensures compliance.
Continuity Management Ensure that IT services and associated business capabilities can be restored in the event of extraordinary external disruptions.
IT Audit Investigate and render opinions on effectiveness of IT governance controls, projects, and processes.
Risk Management Identify and track response to adverse probabilities.
Compliance and E-Records Management Ensure adherence to laws and regulations, including those pertaining to data preservation and destruction.
Continuous Improvement Apply quality and continuous improvement principles to IT service management. Identify and track specific improvement cycles and perspectives. Own the "Improve Service" process.
Capacity Management Predict and mitigate capacity-related issues. Forecast computational service demand as input into asset lifecycle.
Availability Management Predict and mitigate availability issues. Ensure that service levels are met and execute improvement cycles.
Problem Management Identify and address root cause of outages.
IT Communications and Training Coordinate major organizational demands on employee's attention. Ensure consistency of messages. Support and sustain continuous learning in the IT workplace.
Application Management Own the Application Service Lifecycle. Own the overall delivery of applications of computing technology to business problems.
Customer Relationship Management Ongoing management of relationship with sponsors needing IT services.
Solutions Demand Management Own an "Accept Demand" process.
Program and Project Management Own the "Execute Project" process.
Software Engineering Own the major area of software requirements, design, and construction.
Release Management Own the "Deliver Release" process.
Engineering and Operations Own the Infrastructure Service Lifecycle.
Infrastructure Demand Management Own an "Accept Demand" process.
Service Desk First point of contact for the end user community needing to request IT services or report issues (new and failure demand). May also provide gateway for IT to IT services.
IT Operations Responsible for IT service delivery and support on a day-to-day basis.
Change Management Own the "Complete Change" process.
Configuration Management Maintain correct and current records of IT systems and their relationships.
Event Management Aggregate, analyze, and track IT management events and forward as appropriate for investigation and resolution.
Incident Management Own the "Restore Service" process.
Service Level Management Ensure that service expectations are correctly set and managed to.
Infrastructure Engineering Manage the provisioning, configuration, and ongoing operation of computing resources at the most detailed level.
End User Platforms Own the provisioning and maintenance of all end user–facing "edge" devices and assets.
Computing Management Manage servers, midranges, and mainframes; focus on core computing (e.g., operating system level).
Storage Management Manage Storage Area Network and Network Attached Storage.
Database Management Manage the infrastructure of large shared data repositories and the software products that enable them.
Middleware Management Manage messaging, application integration, SOA, and related forms of specialized IT infrastructure.
Network Management Manage data and voice communications. Coordinate with external providers.
Facilities Management Manage physical buildings, data centers, and related assets.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B978012385017100002X

matlab Programming

James C. Squire P.E., Ph.D. , Julie Phillips Brown Ph.D. , in Programming for Electrical Engineers, 2021

Example: Plot a Lowpass Filter's Response Given a Cutoff Frequency

Courses in Signals and Systems will develop the following equation that describes a lowpass filter:

H ( f ) = 1 1 + j ( f f o )

In this equation, f is the input frequency in Hz and f o is the cutoff frequency in Hz. The filter is designed to pass frequencies less than f o and block frequencies above it. H(f) is a complex function of f, since it has a j term in the denominator.

Recall

A Bode-style plot uses semilogx and plots the vertical (amplitude) axis in dB. To find the value in dB of a complex number z, take 20 log10|z|.

Problem

Create a function called lowpass() that takes a cutoff frequency f o and creates a Bode plot of the magnitude of |H(f)| from 1   f    100.

Solution

Since the function takes one number (f o ) and returns nothing (it creates a plot), the function definition line and help lines are

function lowpass(fo)

% lowpass(fo) creates a Bode-style plot of the

% response of a lowpass filter with a cutoff of fo

Then create a frequency vector, logarithmically spaced between 1 and 100Hz:

f   =   logspace(0, 2, 50); % 1-100Hz   =   10^0 – 10^2

Next, compute H(f):

H   =   1./(1+j∗(f/fo)); % since using vectors, use ./

Now, change that into dB for the Bode plot (see the Recall inset above):

dB   =   20∗log10(abs(H)); % find the magnitude of H in dB

Complete the plot and label it:

semilogx(f,dB)

title('Lowpass filter')

xlabel('Frequency (Hz)')

ylabel('Amplitude (dB)')

grid('on')

Save the program as lowpass.m and call it from the command line for a 10Hz lowpass filter as follows:

lowpass(10)

The following Bode-style plot is displayed:

Note that none of the variables created inside the function remain after the function runs.

Practice Problems

9.

Modify the above function to return the filter response in dB rather than plotting it. For example, using f o  =   10, a vector of 50 values are returned, the first of which is −0.0432. ©

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128215029000043

Z-Transform

M. Edwin Sawan , in Encyclopedia of Physical Science and Technology (Third Edition), 2003

III Transfer Function

One of the basic properties of the z -transform is that convolution is transformed into multiplication. This gives rise to the transfer function definition as the ratio between the output and the input of a dynamic system under zero initial conditions. Transfer function is a useful tool of modeling, analysis, and design of dynamic systems. Its poles, also known as the characteristic roots, determine the system stability. A system is stable if all its poles lie inside the unit circle centered at the origin of the z-plane. Transfer functions are also used to develop block simulation diagrams that are essential for the analysis and design of dynamic systems.

There are several methods to test the stability of discrete-time systems without actually computing the poles of the transfer function. A frequently used method is based on the Routh–Hurwitz criterion for continuous systems, where stability is indicated by transfer function poles lying on the left half of the complex plane. The method starts with applying the bilinear transformation

z = ( w + 1 ) / ( w 1 )

to the discrete transfer function. This transformation maps the transfer function from the z-plane to another complex plane, the w-plane. It is clearly seen that the inside of the unit circle in the z-plane is mapped into the left half of the w-plane. Hence, the Routh–Hurwitz stability criterion can be used to determine the stability of the transfer function represented in the w-plane.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B0122274105008334

Function M-files

Brian D. Hahn , Daniel T. Valentine , in Essential MATLAB for Engineers and Scientists (Seventh Edition), 2019

Summary

Good structured programming requires real problem-solving programs to be broken down into function M-files.

The name of a function in the function definition line should be the same as the name of the M-file under which it is saved. The M-file must have the extension .m.

A function may have input and output arguments, which are usually its only way of communicating with the workspace. Input/output arguments are dummy variables (placeholders).

Comment lines up to the first non-comment line in a function are displayed when help is requested for the function.

Variables defined inside a function are local variables and are inaccessible outside the function.

Variables in the workspace are inaccessible inside a function unless they have been declared global.

A function does not have to have any output arguments.

Input arguments have the appearance of being passed by value to a function. This means that changes made to an input argument inside a function are not reflected in the actual input argument when the function returns.

A function may be called with fewer than its full number of input/output arguments.

The functions nargin and nargout indicate how many input and output arguments are used on a particular function call.

Variables declared persistent inside a function retain their values between calls to the function.

Subfunctions in an M-file are accessible only to the primary function and to other subfunctions in the same M-file.

Private functions are functions residing in a sub-directory named private and are accessible only to functions in the parent directory.

Functions may be parsed (compiled) with the pcode function. The resulting code has the extension .p and is called a P-code file.

The Profiler enables you to find out where your programs spend most of their time.

A handle for a function is created with @.

A function may be represented by its handle. In particular the handle may be passed as an argument to another function.

feval evaluates a function whose handle is passed to it as an argument.

MATLAB first tries to use a name as a variable, then as a built-in function, and finally as one of the various types of function.

Command/function duality means that new commands can be created with function M-files, and that command arguments may be generated with string manipulations.

The Editor/Debugger enables you to work through a script or function line-by-line in debug mode, examining and changing variables on the way.

A function may call itself. This feature is called recursion.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780081029978000130