Abhinav K
Abhinav K

Reputation: 57

what does &fun() refer to in the program?

This is an example problem to demonstrate the use of references in c++. i'm a beginner and this is my first time learning about references. i don't understand why we use &fun(). what does it mean?

#include<iostream>
using namespace std;

    int &fun(){
        static int x = 10;
        return x;
    }
    
    int main(){
        int &y=fun();
        y = 20;
        cout<<fun();
    }

output : 20

Upvotes: 0

Views: 2112

Answers (2)

Austin
Austin

Reputation: 2265

int & means fun() is returning a reference to an int. In main(), that reference is assigned to y, and the value of y is modified to 20, also changing the value of x to 20.

Upvotes: 1

Adam Kotwasinski
Adam Kotwasinski

Reputation: 4564

Equivalent syntax is int& fun(). So this function returns a reference to 'x' (that is static), so later in main you can modify it (y = 20 does change the x inside the function). So another invocation returns 20, as the x had been changed.

Upvotes: 2

Related Questions