Sign in to follow this  
JasonL220

union passing

Recommended Posts

JasonL220    132
i have some unions that i want to pass to function but i'm not sure what the syntax should be, would making them global be bad programming practice?

Share this post


Link to post
Share on other sites
rip-off    10978
if your union is in some header file, then

union UnionName{

};

void someFunction( UnionName value );

in c

typedef union{

}UnionName;

void someFunction( UnionName value );

what is the actual problem you have / what are you trying to do

Share this post


Link to post
Share on other sites
JasonL220    132
i'm making a pong clone and read the unions help minimise thememory useage by the program. So if i did this


union VectorSpeed
{
float xspeed;
float yspeed;
}

int main()
{
VectorSpeed ball;
changespeed(ball);
}

int changespeed(union ball)
{
ball.xspeed++;
ball.yspeed--;
return ball;
}


would that work? how would i do it with references?

Share this post


Link to post
Share on other sites
stylin    758
union VectorSpeed {

float xspeed;
float yspeed;
}

int changespeed( VectorSpeed & );

int main() {

VectorSpeed ball;
changespeed( ball );
...
}

void changespeed( VectorSpeed & some_union ) {

some_union.xspeed++;
some_union.yspeed--;
return;
}

Share this post


Link to post
Share on other sites
Ra    1062
I hope you realize that in your union xspeed and yspeed occupy the same space in memory, and therefore will always equal the same value. This is probably not what you intended, and if you want them to be two independent variables you need to use a struct.

Share this post


Link to post
Share on other sites
CTar    1134
Quote:
Original post by JasonL220
so what would i do to pass a struct by reference


You pass it by reference by using the &-sign, just like with unions.


struct VectorSpeed
{
int x,y;
};
void Foo(VectorSpeed& Parameter)
{
// Do stuff
}

Share this post


Link to post
Share on other sites
Ra    1062
struct velocity
{
float x;
float y;
};

void foo(velocity &);

int main(void)
{
velocity ball_v;

foo(ball_v);

...
}

void foo(velocity & v)
{
v.x = 1234.5;
v.y = 5432.1;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this