Pass by Value and Pass by Reference in C

Passing structure to function

There are two methods of passing the structure to the Functions.

1. Pass by Value: It accesses only the copy, and there is no effect on the original value.

2. Pass by Reference: It accesses the memory address and the original value changes.

Passing by Value

Program

#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int age;
int phone_no;
};
int show(struct student S)
{
printf("Name: %s\n",S.name);
printf("Age: %d\n",S.age);
printf("Phone number: %d\n",S.phone_no);
}
int main()
{
struct student S1;
S1.age=21;
strcpy(S1.name,"George");
S1.phone_no=88888;


show(S1);
return 0;
}

 

Output

Explanation

In the above code, we have defined a structure named ‘student’ having ‘roll_no’, ‘name’, and ‘age’ as its members. In the ‘main’ function ‘S1’ is the variable of this ‘student’ structure, and we assigned the values of roll number, name, and age to the structure variable S1. In the ‘show’ function call, we pass the same variable, ‘S1’.

In the definition of the ‘show’ function, we pass a variable ‘S’ of type ‘struct_student’ as the argument. The variable ‘S’ is nothing else but the copy of the variable ‘S1’. Finally, we are printing the values of name, age, and phone number using this function.

Passing by Reference in C

In this method, we will pass the address of the structure variable to the function while calling it in the ‘main’ function. Moreover, we will pass the pointer of a structure variable ‘S’ while declaring the function. Since the pointer is pointing to the variable of the type structure named ‘student’, therefore we will write

‘struct_student’ before the name of the pointer. We will access the members through the pointer using the symbol ‘->’ in the function definition.

Program

#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int age;
int phone_no;
};
int show(struct student *S)
{
printf("Name: %s\n",S->name);
printf("Age: %d\n",S->age);
printf("Phone number: %d\n",S->phone_no);
}
int main()
{
struct student S1;
S1.age=21;
strcpy(S1.name,"George");
S1.phone_no=88888;


show(&S1);
return 0;
}

 

Output

Explanation

The output we get with ‘Pass by reference’ is the same as the output we obtained in ‘Pass by value’. We have to understand both the methods and the difference between them.

Practice as many programs as possible by changing the codes in this article; only then will you can expand your knowledge. Without practice, your knowledge is poison.

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.