Changing the value of something in a function

北城余情 提交于 2019-11-27 08:30:52

问题


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.


回答1:


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



回答2:


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);




回答3:


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



回答4:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!