-2

I made a program that calls this function. I know this because "Int Strength has been called" appears in the output box. However, it will not change the values that I tell it to do. I want it to get integer values from main(), then use them and return the new values. I am using a header file that only contains "int strength(int a, int s, int i)"

int strength(int a, int s, int i)
{
    using namespace std;
    cout << "Int Strength has been called" << endl;
    a = a + i;
    s = s - i;
    return a;
    return s;
}
Lemonizer
  • 83
  • 2
  • 4
  • 14

3 Answers3

7

Multiple errors. Firstly, if you want the arguments to be modified (more precisely, the modification being effective out of the scope of the function), you have to pass the values by reference:

int strength(int &a, int &s, int &i)

Second, you seem to be concerned about return a; return s; returning two values. It doesn't - the very first return encountered exits the function immediately.

  • To match the actual use of OP, I would suggest `void strength(int &a, int &s, const int i);` – FredericS Mar 04 '13 at 16:38
  • 1
    @FredericS Actually, the `const` without the reference is superfluous - `const int &i` or simply `int i` does the job. –  Mar 04 '13 at 16:38
  • Well as `i` is not updated, passing it by value (`int i`) indeed does the job but I believe in const-correctness :) – FredericS Mar 04 '13 at 16:43
  • @FredericS Even if it was updated **and** declared `int i` (i. e. non-const), it **would not affect** the original value. –  Mar 04 '13 at 16:44
  • I totally agree with you, it won't change the behavior, my opinion is the second answer of this question: http://stackoverflow.com/questions/117293/use-of-const-for-function-parameters – FredericS Mar 04 '13 at 16:49
2

The values only change within the function. Variables are passed by value not reference. Use references as the parameters.

 int strength(int& a, int& s, int& i)
suspectus
  • 16,548
  • 8
  • 49
  • 57
1

You're passing by value. You need to pass a pointer to the memory allocated in the caller that contains the data you wish to modify.

void strength(int *a, int *s, int i)
{
    using namespace std;
    cout << "Int Strength has been called" << endl;
    *a += i;
    *s -= i;
}

Then call it thusly:

a = 1;
s = 2;
i = 3;

strength(&a, &s, i);
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • In C++, it's generally considered bad style - since C++ has true references, using pointers for making references is a kind of hack. –  Mar 04 '13 at 16:42
  • An opposing point of view: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments – i_am_jorf Mar 04 '13 at 16:45
  • Even if I understand the cons of the style guide, pointers may be NULL whereas references cannot. This is why I would not use pointers as "out" attributes. – FredericS Mar 04 '13 at 16:56