2-C language - write an auto-increment function, each time it is called, it will increase by 1

question:

        Write an auto-increment function that increments by 1 each time it is called.

Idea:

  1. It means that the function I wrote either affects the value of the main function to achieve self-increment by 1. Or, returns a value and then adds it up in the main function.
  2. That is, one passes the address to the function and the other passes the value.
  3. Passing the address means that the formal parameter can access the main function through the address of the actual parameter, thereby affecting the value of the actual parameter.
  4. Passing a value is just a temporary copy of the formal parameter to the actual parameter, that is, they are two storage spaces, and the mixing does not affect it, just like copying and pasting.
  5. Here we mainly introduce the transfer address.
  6. The actual parameter needs to use the & address character to pass the address of the actual parameter to the formal parameter. In the function, the formal parameter needs to define a pointer variable to receive the address of the actual parameter.
  7. In a function, when incrementing, you need to use the * symbol, which is a content-retrieving symbol. It is also used when defining a pointer. However, when declaring a pointer, it means that the pointer is not fetching the content.
  8. When using *num++, you need to enclose (*num), otherwise the system cannot recognize the real meaning you want to express.
  9. Or you can write *num = *num +1;

code show as below:

#include <stdio.h>
void numplus(int* num)
{
	//(*num)++;//       二选一都可
	*num = *num + 1;
}
int main()
{
	int num = 0;
	int i;
	for (i = 0; i < 5; i++)
	{
		numplus(&num);
		printf("%d\n", num);
	}
}

Guess you like

Origin blog.csdn.net/m0_59844149/article/details/131463160