Site icon T4Tutorials.com

Passing by Value and Passing by Reference using structures in C++

Let us see the C++ program for finding the length of the string by passing values to the function.

We can also pass a structure to a function in two different ways. These two ways are mentioned below;

  1. Passing by Value
  2. Passing by Reference

Passing by Value to the function using structures in C++ (Length of string program)

Passing by Value to the function using structures in C++

//Pass by value using structures in C++
#include<iostream>
#include<string.h>
using namespace std;
struct lengthstring
{
	char str[10];
};
int display(struct lengthstring leng)
{
	lengthstring s;
	int len;
	cout<<"please enter your desired string"<<endl;
	cin>>leng.str;
	len=strlen(leng.str);
	cout<<"The length of desired string is:"<<len<<endl;	
}
int main()
{
	struct lengthstring s1;
	display(s1);
return 0;
}

Output

please enter your desired string

t4tutorials

The length of your desired string is: 11

Passing by Reference to the function using structures in C++ (Length of string program)

Passing by Reference to the function using structures in C++

//Pass by reference using structures in C++
#include<iostream>
#include<string.h>
using namespace std;
struct lengthstring
{
	char str[10];
};
int display(struct lengthstring *leng)
{
	lengthstring s;
	int len;
	cout<<"please enter string"<<endl;
	cin>>leng->str;
	len=strlen(leng->str);
	cout<<"The length of string is="<<len<<endl;	
}
int main()
{
	struct lengthstring s1;
	display(&s1);
return 0;
}

Output

please enter your desired string

welcome

The length of your desired string is: 7

Exit mobile version