Changing the value of something in a function

主宰稳场 提交于 2019-11-28 14:27:31

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
ChrisC

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 ) 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
Richard Schneider

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