A simple difference when passing a pointer as a function argument

When I was studying Go, I rediscovered (or rather reviewed) it, and I realized that the basics were missing. I think I learned it when I studied C language, but I'm completely out of my mind, so I'll write it down. In this article, C and Go are used as examples.

Pass by value

First, let's pass the value of the variable to the function normally.

#include<stdio.h>

int plus1(int x){
	x = x + 1 ;
	return x ;
}

int main(void){
	int a ;
	a = 1 ;
	
	plus1(a);
	
	printf("a = %d\n",a);//a =Is displayed as 1
	return 0;
}
package main
import "fmt"

func plus1(x int) int{
	x = x + 1
	return x
}

func main(){
	a := 1
	a1 := plus1(a)
	
	fmt.Println("a =", a)	//a =Is displayed as 1
	fmt.Println("a + 1 =", a1)	//a + 1 =2 is displayed
}

Pass by pointer

Next, let's pass a pointer.

#include<stdio.h>

int plus1(int *x){
	*x = *x + 1 ;
	return *x ;
}

int main(void){
	int a ;
	a = 1 ;
	
	plus1(&a);
	
	printf("a = %d\n",a);//a =2 is displayed
	return 0;
}
package main
import "fmt"

func plus1(x *int) int{
	*x = *x + 1
	return *x
}

func main(){
	a := 1
	a1 := plus1(&a)
	
	fmt.Println("a =", a)	//a =2 is displayed
	fmt.Println("a + 1 =", a1)	//a + 1 =2 is displayed
}

The result has changed.

Summary

If you pass the variable ʻa`` normally, the function will be passed a copy of ʻa. So the changes are not applied to the original `ʻa. When the ~~ pointer is passed, the address where ʻa`` is stored is directly modified, so the process of" adding 1 to a "is changed to the number in the address pointed to by a. It has changed to the process of "adding 1". So in the end, the value of the variable ʻa`` looking at the same place also goes from 1 to 2. ~~

Finally

It's natural for someone who can do it, but I've kept it ambiguous so far, so I took this opportunity to review it. I hope it helps someone even a little.

Recommended Posts

A simple difference when passing a pointer as a function argument
Utilization of lambda (when passing a function as an argument of another function)
Format when passing a long string as an argument of python
Try adding a simple image baking function as an add-on
The story I was addicted to when I specified nil as a function argument in Go
[python] Callback function (pass function as argument)
Precautions when using a list or dictionary as the default argument
Precautions when pickling a function in python
A simple IDAPython script to name a function
When a local variable with the same name as a global variable is defined in the function