Using reference parameters.

I am writing a function to do percent values... I need to return them all to the main function.. I know OF reference parameters.. not how to use them or how to even set it up for something like this >.> any help is much appreciated ^^

1
2
3
4
vhsPer = vhsCnt/totCnt * 100;
dvdPer = dvdCnt/totCnt * 100;
gamePer = gameCnt/totCnt * 100;
return;


thats what im dealing with at the moment. thanks in advance ^^
Try the following, which should help you understand references

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

void foo1( int x ) {
    x = 5;
}

void foo2( int& x ) {
    x = 6;
}

void foo3( int* x ) {
    *x = 7;
}

int main() {
    int a = 1, b = 1, c = 1;

    foo1( a );
    std::cout << a << std::endl;

    foo2( b );
    std::cout << b << std::endl;

    foo3( &c );
    std::cout << c << std::endl;
}

i would also suggest you put all three variables in a class/struct. that way you don't end up with lots of arguments

1
2
3
4
5
6
struct foo
{
  float vhsPer;
  float dvdPer;
  float gamePer; 
};


if in a struct you could return the struct instead:

1
2
3
4
5
6
7
foo calcPerc()
{
    foo f;
    f.vhsPer = ...;
    ..
    return f;
}

generally speaking - IMHO - returning a value with the function is more readable than returning via several arguments.

Last edited on
Topic archived. No new replies allowed.