C Tutorial/Function/Function Parameter — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...)  | 
				Admin (обсуждение | вклад)  м (1 версия: Импорт контента...)  | 
				
(нет различий) 
 | |
Текущая версия на 10:32, 25 мая 2010
Содержание
Call by reference
#include<stdio.h>
main ( )
{
    int i;
    i = 0;
    printf (" The value of i before call %d \n", i);
    f1 (&i);
    printf (" The value of i after call %d \n", i);
}
 f1(int *k)
{
    *k = *k + 10;
}The value of i before call 0 The value of i after call 10
Cube a variable using call-by-reference with a pointer argument
#include <stdio.h>
void cubeByReference( int *nPtr );
int main()
{
   int number = 5;
   printf( "The original value of number is %d", number );
 
   cubeByReference( &number );
   printf( "\nThe new value of number is %d\n", number );
   return 0;
}
void cubeByReference( int *nPtr )
{
   *nPtr = *nPtr * *nPtr * *nPtr;  /* cube *nPtr */
}The original value of number is 5 The new value of number is 125
Cube a variable using call-by-value
#include <stdio.h>
int cubeByValue( int n );
int main()
{
   int number = 5; 
   printf( "The original value of number is %d", number );
   
   /* pass number by value to cubeByValue */
   number = cubeByValue( number );
   printf( "\nThe new value of number is %d\n", number );
   return 0;
}
int cubeByValue( int n ) {
   return n * n * n;   
}The original value of number is 5 The new value of number is 125
Parameter passing
Information can be passed into function.
   
#include<stdio.h>
main ( )
{
    int i;
    i = 0;
    printf (" The value of i before call %d \n", i);
    f1 (i);
    printf (" The value of i after call %d \n", i);
}
f1 (int k)
{
    k = k + 10;
}The value of i before call 0 The value of i after call 0
Pass variables to function
#include <stdio.h>
float average(float x, float y)
{
  return (x + y)/2.0f;
}
int main(void)
{
  float value1 = 1.0F;
  float value2 = 2.0F;
  float value3 = 0.0F;
  value3 = average(value1, value2);
  printf("\nThe average is: %f\n",  value3);
  return 0;
}The average is: 1.500000
Use pointer as function parameter
#include <stdio.h>
int change(int* pnumber);              /* Function prototype              */
int main(void)
{
  int number = 10;
  int *pnumber = &number;
  int result = 0;        
  result = change(pnumber);
  printf("\nIn main, result = %d\tnumber = %d", result, number);
  return 0;
}
int change(int *pnumber)
{
  *pnumber *= 2;
  printf("\nIn function change, *pnumber = %d\n", *pnumber );
  return *pnumber;
}In function change, *pnumber = 20
     
     In main, result = 20    number = 20