1

This is a test case for something larger, which is why it is written the way is. How could I make this bit of code so that a's value would keep incrementing? In my project I call a function that parses a line from a file. I need to set values of a struct to certain values that were set in the function call (the parameters of the function were initialized in the main function, like the code below).

int increment(int a)
{
    a++;
    return 0;
}
int main()
{
    int a =0;
    int b =0;
    while( b<5){
        increment(a);
        b++;
        cout << "a is: " << a << ". And b is: " << b << "\n";
    }
    system("PAUSE");
}

Thanks.

alk
  • 69,737
  • 10
  • 105
  • 255
Will Nasby
  • 1,068
  • 2
  • 16
  • 39
  • In many situations, you would be better off returning the incremented value, as in `int increment(int a) {return a+1;}`. The you call it as `a = increment(a)`. – Sergey Kalinichenko Feb 10 '13 at 01:22

4 Answers4

3

Pass its address to increment

void increment(int *a){
  (*a)++;  
}
increment(&a);
//Using the address of operator pass in the address of a as argument
Lews Therin
  • 10,907
  • 4
  • 48
  • 72
1

You could use a pointer: See Passing by reference in C for a similar question.

Also, you could just modify your increment function to return the incremented value of a, and call it in main like the following:

a = increment(a);

Community
  • 1
  • 1
ChrisC
  • 2,461
  • 1
  • 16
  • 25
0

You could:

  • Declare static int a = 0; return a++;
  • Change the signature to int increment( int* a ) and return *a++;
  • Declare a in file scope of the same source file as increment()
  • Make a global
  • Do this in C++ and pass a by reference
Davislor
  • 14,674
  • 2
  • 34
  • 49
-1

You are passing a by value, so the value of a can never be changed.

One solution is:

int increment (int a) { return a + 1; }

Then in your loop:

a = increment(a);

Another solution is to pass a by reference (a pointer)

void increment (int *a) { *a = *a + 1; }

and in the loop

increment(&a);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73