<< Chapter < Page Chapter >> Page >

Lets look at an example program:

#include<stdio.h>#include<conio.h>int mult ( int x, int y ); int main(){ int x;int y; printf("Please input two numbers to be multiplied: ");scanf("%d%d",&x,&y); printf("The product of your two numbers is %d\n", mult ( x, y )) ;return 0; getch();} int mult ( int x, int y ){ return x * y;}

Parameters passing

The parameters of a function are ordinary local variables. The program creates them, and initializes them with the values of the corresponding arguments, when a function call occurs. Their scope is the function block. A function can change the value of a parameter without affecting the value of the argument in the context of the function call. In the following listing, the factorial( ) function, which computes the factorial of a whole number, modifies its parameter n in the process.

//factorial( ) calculates n!, the factorial of a non-negative number n. // For n>0, n! is the product of all integers from 1 to n inclusive. // 0! equals 1.// Argument: A whole number, with type unsigned int. // Return value: The factorial of the argument, with type long double.long double factorial(register unsigned int n) {long double f = 1; while ( n>1 ) f *= n--;return f; }

Although the factorial of an integer is always an integer, the function uses the type long double in order to accommodate very large results. As the above listing illustrates, you can use the storage class specifier register in declaring function parameters. The register specifier is a request to the compiler to make a variable as quickly accessible as possible. No other storage class specifiers are permitted on function parameters.

Arrays as function parameters

If you need to pass an array as an argument to a function, you would generally declare the corresponding parameter in the following form:

type name[ ]

Because array names are automatically converted to pointers when you use them as function arguments, this statement is equivalent to the declaration:

type *name

When you use the array notation in declaring function parameters, any constant expression between the brackets ([ ]) is ignored. In the function block, the parameter name is a pointer variable, and can be modified. Thus the function addArray() in the following listing modifies its first two parameters as it adds pairs of elements in two arrays.

// addArray( ) adds each element of the second array to the // corresponding element of the first (i.e., "array1 += array2", so to speak).// Arguments: Two arrays of float and their common length. // Return value: None.void addArray( register float a1[ ], register const float a2[ ], int len ) {register float *end = a1 + len; for ( ; a1<end; ++a1, ++a2 ) *a1 += *a2;}

An equivalent definition of the addArray() function, using a different notation for the array parameters, would be:

void addArray( register float *a1, register const float *a2, int len ) { /* Function body as earlier. */ }

An advantage of declaring the parameters with brackets ([ ]) is that human readers immediately recognize that the function treats the arguments as pointers to an array, and not just to an individual float variable. But the array-style notation also has two peculiarities in parameter declarations :

  • In a parameter declaration and only there C allows you to place any of the type qualifiers const, volatile, and restrict inside the square brackets. This ability allows you to declare the parameter as a qualified pointer type.
  • Furthermore, in C you can also place the storage class specifier static, together with a integer constant expression, inside the square brackets. This approach indicates that the number of elements in the array at the time of the function call must be at least equal to the value of the constant expression.

Here is an example that combines both of these possibilities:

int func( long array[const static 5] ){ /* ... */ }

In the function defined here, the parameter array is a constant pointer to long, and so cannot be modified. It points to the first of at least five array elements.

In the following listing, the maximum( ) function's third parameter is a two-dimensional array of variable dimensions.

// The function maximum( ) obtains the greatest value in a // two-dimensional matrix of double values. // Arguments: The number of rows, the number of columns, and the matrix.// Return value: The value of the greatest element. double maximum( int nrows, int ncols, double matrix[nrows][ncols] ){ double max = matrix[0][0];for ( int r = 0; r<nrows; ++r ) for ( int c = 0; c<ncols; ++c ) if ( max<matrix[r][c]) max = matrix[r][c];return max; }

The parameter matrix is a pointer to an array with ncols elements.

Pointers as function parameters

Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function. For instance, a sorting routine might exchange two out-of-order arguments with a function called swap. It is not enough to write

swap(a, b);

where the swap function is defined as

void swap(int x, int y) /* WRONG */ {int temp; temp = x;x = y; y = temp;}

Because of call by value, swap can't affect the arguments a and b in the routine that called it. The function above swaps copies of a and b.

The way to obtain the desired effect is for the calling program to pass pointers to the values to be changed:

swap(&a,&b);

Since the operator&produces the address of a variable,&a is a pointer to a. In swap itself, the parameters are declared as pointers, and the operands are accessed indirectly through them.

void swap(int *px, int *py) /* interchange *px and *py */ {int temp; temp = *px;*px = *py; *py = temp;}

{

Pictorially in [link]

swap function with pointer parameters

Questions & Answers

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?

Ask