Advertisement

returning values

Started by January 01, 2001 11:09 AM
4 comments, last by nika 24 years, 1 month ago
Hi all, can i make a function that returns 2 or more values?? Lets say i have a funktion like this: float test_func(GLfloat x, GLfloat y) { x=x+1; y=y+1; //is something like this possible return x,y; //??? }
Hi!

One possibility would be to use a structure for the return value:
  typedef struct{  float x, y;} ret;ret test_func (float x, float y){  ret rv;  rv.x = x + 1;  rv.y = y + 1;  return rv;}   


However, I would pass the variables that shall contain the return values by refernce (a pointer in C):
  void test_func (float xIn, float yIn, float *xOut, float *yOut){  *xOut = xIn + 1;  *yOut = yIn + 1;}   

This can be solved even more elegant with the C++ refernce operator "&".

Edited by - VolkerG on January 1, 2001 12:31:39 PM
Advertisement

No, it is not possible to return more than one value from a function.

If you want to get back more than one value you will have to use either use pointers or pass the values you want returned by reference.

Ex:

//Pass by reference
void test_func(GLfloat& x, GLfloat& y)
{
x=x+1;
y=y+1;
}

// Usage, modifies values passed directly
test_func(x, y);


Ex:
//Using pointers
void test_func(GLfloat* x, GLfloat* y)
{
*x=*x+1; // *x dereferences and *yields* the variable pointed
*y=*y+1; // to by the pointer x
}

// Usage, must pass a pointer to the variables, &variable gives
// the address / pointer to it
test_func(&x, &y);
Thx for your tip.

I tried to use pointers but i still have a problem.

here is my exact code:

float complete_collision(GLfloat *x_move, GLfloat *y_move, GLfloat *z_move,
GLfloat x_stay, GLfloat y_stay, GLfloat z_stay,
GLfloat distance)
{


*x_move=exp_collision_detection_x(*x_move, *y_move, *z_move,
x_stay, y_stay, z_stay,
distance);
*y_move=exp_collision_detection_y(*x_move, *y_move, *z_move,
x_stay, y_stay, z_stay,
distance);
*z_move=exp_collision_detection_z(*x_move, *y_move, *z_move,
x_stay, y_stay, z_stay,
distance);
return 0;
}


i call the function with this code:


complete_collision (ax, ay, az, 5, 5, -4, 2);


While compileing i get an error: Incompatilbe type conversion

What''s to do?
You need to pass the variable''s address for the first 3 arguments
of this function.

The ''&'' operator is used to reference or get the address of
a variables(eg. ''&ax'' gets the address of ax). This is a
unary operator.

Your function should be called like this.

GLfloat ax,ay,az;
...
complete_collision (&ax, &ay, &az, 5, 5, -4, 2);

Study how to reference and dereference pointers.
totis viribus
Thx
with
complete_collision (&ax, &ay, &az, 5, 5, -4, 2);
it works!

This topic is closed to new replies.

Advertisement