Functions of Structs

I was wondering if there was any way to make a function whose parameters can be a struct, such that any variable inside of the structure could be a valid parameter for the function. For example,
1
2
3
4
5
6
7
8
9
10
struct sample {

int x, y, z, a, b, c;

};


void square_root (sample){ //Ideally, function returns square root of any number in the struct sample.
//Code for function
}


Does anyone know how to do this? I tried this code but it doesn't seem to work. Thanks for the help!
That's correct, but its recommended that you pass the struct as a reference so that the cpu doesn't create a copy of the struct on the stack and only references the location in memory.

1
2
3
4
float square_root(sample& Sample)
{
return sqrt(Sample.x);
};
You can write a member function of the stracture that will do the task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct sample {

	int x, y, z, a, b, c;
	const sample square_root() const
	{
		sample t = { ( int ) std::sqrt( ( double ) x ),
	  	             ( int ) std::sqrt( ( double ) y ),
	                     ( int ) std::sqrt( ( double ) z ),
		             ( int ) std::sqrt( ( double ) a ),
		             ( int ) std::sqrt( ( double ) b ),
		             ( int ) std::sqrt( ( double ) c ) };

		return ( t );
	}
};

sample s1 = { 4, 9, 16, 25, 36, 49 };
sample s2 = s1.square_root();

std::cout << s2.x << ' ' << s2.y << ' ' << s2.z << ' ' 
      << s2.a << ' ' << s2.b << ' ' << s2.c << std::endl;
Last edited on
Topic archived. No new replies allowed.