Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency
Open In App
Next Article:
Returning Pointer from a Function in Go
Next article icon

Returning Pointer from a Function in Go

Last Updated : 17 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Prerequisite: Pointers in Go and Passing Pointers to Function 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. CPP
// C++ program to return the // pointer from a function #include <iostream> using namespace std;  // taking a function having // pointer as return type int* rpf(int);  int main() {      int n = 745;      // displaying the value of n     cout << n << endl;      // calling the function     cout << *rpf(n) << endl; }  // defining function int* rpf(int n1) {      // taking a local variable     // inside the function     int lv = n1 * n1;      // remove comment or make the above     // declaration as static which     // result into successful     // compilation     // static int lv = n1 * n1;      // this will give warning as we     // are returning the address of     // the local variable     return &lv; } 
Warnings
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;
Output:
  745  
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. Example: c
// Go program to return the // pointer from the function package main  import "fmt"  // main function func main() {      // calling the function     n := rpf()      // displaying the value     fmt.Println("Value of n is: ", *n)  }  // defining function having integer // pointer as return type func rpf() *int {      // taking a local variable     // inside the function     // using short declaration     // operator     lv := 100      // returning the address of lv     return &lv } 
Output:
  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.

Next Article
Returning Pointer from a Function in Go

A

anshul_aggarwal
Improve
Article Tags :
  • Go Language
  • Golang-Pointers
  • Golang

Similar Reads

    reflect.Pointer() Function in Golang with Examples
    Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Pointer() Function in Golang is used to get the v's value as a uintptr. To access this function, one needs to imp
    2 min read
    Passing Pointers to a Function in Go
    Prerequisite: Pointers in Go Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also pass the pointers to the function like the variables. There are two ways to do this as follows: Create a pointer and simply pass it to
    3 min read
    io.WriteString() Function in Golang with Examples
    In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The WriteString() function in Go language is used to write the contents of the stated string "s" to the writer "w", which takes
    2 min read
    Recursive Anonymous Function in Golang
    Recursion is a process in which a function calls itself implicitly or explicitly and the corresponding function is called recursive function. Go language supports special feature called anonymous function. It is a function that doesn’t contain any name. It is used to create an inline function. Recur
    2 min read
    main and init function in Golang
    The Go language reserve two functions for special purpose and the functions are main() and init() function.main() functionIn Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a spec
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences