Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Passing Arguments to Functions by Reference in C

August 28, 2013 Posted by: GPA Views: 570 0 comments

Problem

How to pass arguments to functions by reference in C?

Solution

There are two methods to pass arguments to a function first one - call-by-value and second one- call-by-reference. All arguments in C are passed by value. One function can return one value from a called function. But in some situation we must return more than one value. To solve this problem we can use pointers. The program below presents two versions of a function that return one value and two value - passByValue and passByReference. First one returns one value multiplied by 2 and second one returns two values multiplied by 2.

Example:

   

#include <stdio.h>
#include <stdlib.h>
//prototype of functions
int passByValue(int firstvariable);
void passByReference(int *firstvariable, int *secondvariable);
int main(int argc, char *argv[])
{
   int firstvariable=5;//first variable
   int secondvariable=10;//second variable
   //show result
   printf("passByValue result is %d",passByValue(firstvariable));
   passByReference(&firstvariable,&secondvariable);//call function passByReference
printf("\npassByReference result for firstvariable is %d",firstvariable);
   printf("\npassByReference result for secondvariable is %d\n",secondvariable);
   system("PAUSE");
   return 0;
}
//this function return 1 variable passing by value
int passByValue(int firstvariable){
   return firstvariable*2;
}
//this function return 2 variables using pointer
void passByReference(int *firstvariable, int *secondvariable){
     *firstvariable*=2;
     *secondvariable*=2;
} 

Output

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe