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.
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
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);
You could:
- Declare
static int a = 0;
return a++;
- Change the signature to
int increment( int* a )
andreturn *a++;
- Declare
a
in file scope of the same source file asincrement()
- Make
a
global - Do this in C++ and pass
a
by reference
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);
来源:https://stackoverflow.com/questions/14793576/changing-the-value-of-something-in-a-function