The selection of the argument passing depends on the situation.
- If the data object is small, such as a built-in data type or a particular field of an array or of a structure then pass it by call by value.
- If the data object is an array, call by reference should be choice.
- If the data object is a good-sized structure, call by reference should be choice to save the time and space needed to copy a structure.
- If a variable is not set at the caller function and wish to update the variable at the called function and read the same value in caller function, then call by reference is the only choice.
Code snippet
Structure is passed as reference:
#include <stdio.h>
struct student{
int roll;
char *name;
};
void call_by_ref_structure(struct student *stu)
{
stu->roll = 4;
stu->name ="techacces";
}
int main()
{
struct student st;
call_by_ref_structure(&st);
printf("\n Name of the student is : %s", st.name);
printf("\n Roll number of the student is : %d\n", st.roll);
return 0;
}
Output:
Name of the student is : techacces
Roll number of the student is : 4
Example-2:
When value need to be updated the called function
#include <stdio.h>
void update_value(int *value)
{
*value = 10;
}
int main()
{
int val;
update_value (&val);
printf("\n Updated value is : %d", val);
return 0;
}
Output:
Updated value is : 10
Categories: C Language
Leave a Reply