Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function in Golang. In C/C++, it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable.
Example: In the below program, the line of code(int lv = n1 * n1;) will give warning as it is local to the function. To avoid warnings make it static.
prog.cpp: In function ‘int* rpf(int)’:
prog.cpp:24:9: warning: address of local variable ‘lv’ returned [-Wreturn-local-addr]
int lv = n1 * n1;
The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also get removed which causes the local variables of functions goes out of scope. Making it static will resolve the problem. As static variables have a property of preserving their value even after they are out of their scope.
But the Go compiler is very Intelligent!. It will not allocate the memory on the stack to the local variable of the function. It will allocate this variable on the heap. In the below program, variable lv will have the memory allocated on the heap as Go compiler will perform escape analysis to escape the variable from the local scope.
Value of n is: 100
Note: Golang doesn’t provide any support for the pointer arithmetic like C/C++. If you will perform then the compiler will throw an error as invalid operation.
- Function Returning Multiple Values in Go Language
- Golang Pointer to an Array as Function Argument
- reflect.Pointer() Function in Golang with Examples
- Function that takes an interface type as value and pointer in Golang
- Go Pointer to Pointer (Double Pointer)
- Pointer to a Struct in Golang
- How to check pointer or interface is nil or not in Golang?
- How to find the length of the pointer in Golang?
- How to find the capacity of the pointer in Golang?
- How to declare and access pointer variable in Golang?
- How to instantiate Struct Pointer Address Operator in Golang?
- How to find the capacity of Channel, Pointer and Slice in Golang?
- How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
- Pointers to a Function in Go
- Anonymous function in Go Language
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.