• Advertisement
Sign in to follow this  

union passing

This topic is 4502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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
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
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
Sign in to follow this  

  • Advertisement