C function parameter

Example - Parameter passing

Information can be passed into function.


#include<stdio.h>
/*from  w w w .  ja  va 2  s  . c o  m*/
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 code above generates the following result.

Example - Call by reference


#include<stdio.h>
/*w  ww  . j  a v  a  2  s  . com*/
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 code above generates the following result.

Example - Cube a variable using call-by-value


#include <stdio.h>
/* w  w w.  j  a  va  2  s. co  m*/
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 code above generates the following result.

Cube a variable using call-by-reference with a pointer argument.


#include <stdio.h>
/*from   w w w.j ava 2s. co m*/
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 code above generates the following result.

Example - Pass array value into function

The following code show to pass array value into function:

  • by array,
  • by empty array and
  • by pointer

#include <stdio.h>
//from  w w  w. jav  a  2  s.  co  m
void f1(int num[5]), f2(int num[]), f3(int *num);

int main(void)
{
  int count[5] = {1, 2, 3, 4, 5};

  f1(count);
  f2(count);
  f3(count);

  return 0;
}

/* parameter specified as array */
void f1(int num[5])
{
  int i;

  for( i = 0; i < 5; i++) 
      printf("%d ", num[ i ]);
}

/* parameter specified as unsized array */
void f2(int num[])
{
  int i;

  for( i = 0; i < 5; i++) 
      printf("%d ", num[ i ]);
}

/* parameter specified as pointer */
void f3(int *num)
{
  int i;

  for(i = 0; i < 5; i++) 
      printf("%d ", num[ i ]);
}

Example - constant function parameter


#include <stdio.h>
/*  w w  w.j ava  2 s .  co  m*/
void print_str(const char *p);

int main(void)
{
  char str[80];

  printf("Enter a string: ");
  gets(str);

  print_str(str);

  return 0;
}

void print_str(const char *p)
{
  while(*p) 
      putchar(*p++);
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing