Can anybody please give me an example of how to pass a structure via. functions. I hope it is possible, but I'm not sure. If at all possible, I'd like to pass it by value, not really by reference, but it wouldn't hurt to learn both ways.
Printable View
Can anybody please give me an example of how to pass a structure via. functions. I hope it is possible, but I'm not sure. If at all possible, I'd like to pass it by value, not really by reference, but it wouldn't hurt to learn both ways.
It's usually more efficient to pass a structure by reference, as it saves space on the system stack:
Code:
#include <iostream.h>
typedef struct{
int mymember;
} MYSTRUCT;
int SomeFunction(MYSTRUCT &mys){ // passing by reference
mys.mymember=5;
return 0;
}
int main(){
MYSTRUCT struc;
struc.mymember=2;
cout << "mymember=" << struc.mymember << endl; // "mymember=2"
SomeFunction(struc);
cout << "mymember=" << struc.mymember << endl; // "mymember=5"
return 0;
}
You just pass it like any other data type:
Code:struct myStruct
{
int x,y;
}
void myFunc1(myStruct m) // by value
{
cout<<m.x<<" "<<m.y<<endl;
}
void myFunc2(myStruct &m) // by reference
{
cout<<m.x<<" "<<m.y<<endl;
}
int main()
{
myStruct m;
m.x=1;
m.y=2;
myFunc1(m);
myFunc2(m);
return 0;
}
Adding to what he said, if you want to pass it to a function like regular but also save memory, pass it as a const reference.Quote:
Originally posted by poccil
It's usually more efficient to pass a structure by reference, as it saves space on the system stack:
Code:
#include <iostream.h>
typedef struct{
int mymember;
} MYSTRUCT;
int SomeFunction(MYSTRUCT &mys){ // passing by reference
mys.mymember=5;
return 0;
}
int main(){
MYSTRUCT struc;
struc.mymember=2;
cout << "mymember=" << struc.mymember << endl; // "mymember=2"
SomeFunction(struc);
cout << "mymember=" << struc.mymember << endl; // "mymember=5"
return 0;
}
That will work like normal and save space.Code:
struct random{
int i;
int j;
};
int function(const random &num);
Ok. Say I had two switch statements, both are quite long and drawl out, and the only difference is a Name in the structure. All i really want to do is make a function that will accept either of the two structures.
like if i had a structure named MyStru1, and I also had MyStru2. I could pass either into the function. Possible?