Вы находитесь на странице: 1из 8

Functions

Function Declarations
The typical way of getting something done in a C++ program is to call a function to
do it. Defining a function is the way you specify how an operation is to be done. A
function cannot be called unless it has been previously declared.
A function declaration gives the name of the function, the type of the value returned
(if any) by the function, and the number and types of the arguments that must be
supplied in a call of the function. For example:
Void Exit (int);
Char *strcpy(char *to, const char *from);
The semantics of argument passing are identical to the semantics of initialization.
Argument types
are checked and implicit argument type conversion takes place when necessary.
For example:
double sqrt(double);
double r2 = sqrt(2) ;
//call sqrt with ther argument double(2)

Function Definitions
Every function that is called in a program must be defined somewhere (once only).
A function definition is a function declaration in which the body of the function is
presented. For example:
Extern void swarp (int *,int *);
Void Swarp (int * p, int * q)
{
Int t=*p;
Int *p =*q;
*q= t;
}
As shown, the fact that an argument is unused can be indicated by not naming it.
Typically,unnamed arguments arise from the simplification of code or from planning
ahead for extensions. In both cases, leaving the argument in place, although
unused, ensures that callers are not affected by the change.
For example:
Void search(table * t, const char *key, const char *)
A function can be defined to be inline. For example:
#include <iostream>
using namespace std;
int exforsys(int);
void main( )
{
int x;
cout << "n Enter the Input Value: ";

cin>>x;
cout << "n The Output is: " << exforsys(x); //Call is made to the function
exforsys
}
inline int exforsys(int x1)
{
return 5*x1;
}
When the program is compiled, the code present in the inline function exforsys is
replaced in the place of function call in the calling program.
A programmer must make wise choices when to use inline functions. Inline functions
will save time and are useful if the function is very small. If the function is large, use
of inline functions must be avoided.

Static Variables
A local variable is initialized when the thread of execution reaches its definition. By
default, this happens in every call of the function and each invocation of the
function has its own copy of the variable. If a local variable is declared static , a
single, statically allocated object will be used to represent that variable in all calls of
the function. It will be initialized only the first time the thread of execution reaches
its definition. For example:
v o i d f (i n t a )
{
w h i l e (a )
{
s t a t i c i n t n =0 ;//initialized once
i n t x =0 ;//initialized n times
c o u t <<"n =="<<n ++<<",x =="<<x ++<<\ n ;
}
}
i n t m a i n ()
{
f(3);
}

This prints:
n ==0 ,x ==0
n ==1 ,x ==0
n ==2 ,x ==0

A static variable provides a function with a memory without introducing a global


variable that
might be accessed and corrupted by other functions.

Argument Passing
When a function is called, store is set aside for its formal arguments and each
formal argument is initialized by its corresponding actual argument. The semantics
of argument passing are identical
to the semantics of initialization. In particular, the type of an actual argument is
checked against
the type of the corresponding formal argument, and all standard and user-defined
type conversions
For example:

Void f (int val, int &f)


{
Val++;
Ref++;
}
When f() is called, val l++ increments a local copy of the first actual argument,
where as ref ++
increments the second actual argument.
The argument might be declared const to indicate that the reference is used for
efficiency reasons only and not to enable the called function to change the value of
the object:
Void f (const Large &arg)
{
}
The absence of const in the declaration of a reference argument is taken as a
statement of intent to
modify the variable:
Void g (Large &arg)
{
}
Similarly, declaring a pointer argument const t tells readers that the value of an
object pointed to by that argument is not changed by the function. For example:
Void f (const Large *arg)
{
}
The importance of using const arguments increases with the size of a program.

Array Arguments
If an array is used as a function argument, a pointer to its initial element is passed.
For example:
Int strlen (char*);
Void f()
{
Char v[] = an array;
Int i= strlen(v);
Int j=strlen(Hello world);
}
That is, an argument of type T[] will be converted to a T* when passed as an
argument. This
implies that an assignment to an element of an array argument changes the value
of an element of
the argument array.

Value Return

A value must be returned from a function that is not declared void. Conversely, a
value cannot be returned from a void function. For example:
Int f1();
// error no value returned;
{
}
Void f2()
//ok;
{
}
Int f3()
//ok
{
Return 1;
}

Overloaded Function Names


Most often, it is a good idea to give different functions different names, but when
some functions
conceptually perform the same task on objects of different types, it can be more
convenient to give
them the same name. Using the same name for operations on different types is
called overloading.
For example:
Void Print(int x)
{
}
Void Print (double x)
{
}

Overloading and Return Type


C + + allows multiple functions in the same scope (global, in same namespace,
static functions in a source file) can have identical name, but different call
parameters (number of parameters, type
each parameter).
For example:
int compare(int n1, int n2);
int compare(float x1, float x2);
bool compare(float x1, float x2); // li
int compare(string& s1, string& s2);
int compare(const string& s1, const string& s2);
To determine the correct function call, the compiler will be priority function which
have correct parameter types as parameters when calling, if not it will use any
function that the parameters can be transferred to.
For example:
string ss1("xyz"), ss2("mpnq");
const string cs("aaa");
compare(1.3, 2.5);
// li

compare("abcd", "12345"); // hm 5
compare(ss1, ss2);
// hm 4
compare(ss1, cs);
// hm 5

Default Arguments
A default parameter is a function parameter that has a default value provided to
it. If the user does not supply a value for this parameter, the default value will be
used. If the user does supply a value for the default parameter, the user-supplied
value is used.
For example:
void PrintValues(int nValue1, int nValue2=10)
{
using namespace std;
cout << "1st value: " << nValue1 << endl;
cout << "2nd value: " << nValue2 << endl;
}
int main()
{
PrintValues(1); // nValue2 will use default parameter of 10
PrintValues(3, 4); // override default value for nValue2
}

This program produces the following output:


1st
2nd
1st
2nd

value:
value:
value:
value:

1
10
3
4

In the first function call, the caller did not supply an argument for nValue2, so the
function used the default value of 10. In the second call, the caller did supply a
value for nValue2, so the user-supplied value was used.
Default parameters are an excellent option when the function needs a value that
the user may or may not want to override.
A function can have multiple default parameters:
void PrintValues(int nValue1=10, int nValue2=20, int nValue3=30)
{
cout << "Values: " << nValue1 << " " << nValue2 << " "
<<nValue3<<endl;
}

Given the following function calls


PrintValues(1, 2, 3);
PrintValues(1, 2);
PrintValues(1);
PrintValues();

The following output is produced:


Values:
Values:
Values:
Values:

1 2 3
1 2 30
1 20 30
10 20 30

Unspecified Number of Arguments

Using the ellipsis, ..., with C++ function prototypes, means that the function can be
specified with an unknown number and type of parameters. This feature can be
used to suppress parameter type checking and to allow flexibility in the interface to
the function. C++ allows functions be to declared with an unspecified number of
arguments. Ellipsis marks are used to indicate this, as follows:
The function printf(), from header stdio.h, is declared as
int printf( char *, ... );
Calls to printf() must have at least one argument, namely a string, beyond this, the
additional arguments are unspecified both in type and in number. Argument
checking is turned off when a function is declared to have an unspecified number of
arguments. It is therefore recommend against using this capability unless it is
absolutely necessary.

Pointer to Function
A function pointer is a variable that stores the address of a function that can later
be called through that function pointer.
For example:
#include <stdio.h>
#include <stdlib.h>
void func(int);
main(){
void (*fp)(int);
fp = func;
(*fp)(1);
fp(2);
}

exit(EXIT_SUCCESS);

void
func(int arg){
printf("%d\n", arg);
}

If you like writing finite state machines, you might like to know that you can have an
array of pointers to functions, with declaration and use like this:
For example:
Void Cong(int a,int b)
{
Count<<a+b=<<a+b;

}
Void Tru(int a,int b)
{
Count<<a-b=<<a-b;
}
Void Nhan(int a,int b)
{
Count<<a*b=<<a*b;
}
Void Chia(int a,int b)
{
Count<<a/b=<<a/b;
}
Void main()
{
Clrscr();
Void (*f[4])(int a,int b)={Cong, Tru,Nhan,Chia};
Int m,n;
Count <<Nhap m,n;
Cin>>m>>n;
For(int i=0;i<4;i++)
f[i](m,n);
Getch();

Вам также может понравиться