structure copying

in my c++ book the following question was given
"write a program to copy one structure variable to another without using any built-in functions

and following code was given in solution
1
2
3
4
5
6
7
8
9
10
11
12
13
main()
{
	struct abc
	{
		int age;
	}; 
	abc s1,s2,t;
	cin>>s1.age;
	t.age=s1.age;//
	s2.age=s1.age;//
	s1.age=t.age;//
	cout<<s2.age;
}

can someone explain this to me why we have did this
we could have used this instead
1
2
3
4
5
6
7
8
9
10
11
main()
{
	struct abc
	{
		int age;
	}; 
	abc s1,s2;
	cin>>s1.age;
	s2.age=s1.age;//
	cout<<s2.age;
}

please reply ASAP
Yes, I agree your version works as well. Not really sure why they included a second object "t". I guess they wanted to show you that it could be copied to more than one variable.

Example:

t = s1;
s2 = s1;
s1 = t;


So I guess it is just for the example.
ya you are right but yet again
why they returned the value i mean in :

t = s1;
s2 = s1;
s1 = t;

if they wanted to copy it to two variables they could have written only
t = s1;
s2 = s1;

so why they included the last line i.e:
t = s1;
s2 = s1;
No clue. But it is not needed so you are fine.
Re-read the question. Are you supposed to copy one structure variable to another or are you supposed to exchange two structure variables? The sample solution exchanges s1.age and s2.age.
Topic archived. No new replies allowed.