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
- Go Pointer to Pointer (Double Pointer)
- Pointer to a Struct in Golang
- How to find the capacity of the pointer in Golang?
- How to find the length of the pointer in Golang?
- Pointers to a Function in Go
- Anonymous function in Go Language
- Function Arguments in Golang
- Higher-Order Function in Golang
- main and init function in Golang
- How to pass an Array to a Function in Golang?
- Function as a Field in Golang Structure
- How to pass a Slice to Function in Golang?
- atomic.AddInt64() Function in Golang With Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.