The Wayback Machine - https://web.archive.org/web/20241204071637/https://www.geeksforgeeks.org/can-we-use-function-on-left-side-of-an-expression-in-c-and-cpp/
Open In App

Can We Use Function on Left Side of an Expression in C and C++?

Last Updated : 21 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, it is not possible to have function names on the left side of an expression, but it’s possible in C++. 

How can we use the function on the left side of an expression in C++? 

In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenever a function returns a reference, an implicit pointer is being returned to its return value. Therefore, through this, we can use a function on the left side of an assignment statement. The above has been demonstrated using the example given below,

CPP




// CPP program to demonstrate using a function on left side
// of an expression in C++
#include <iostream>
using namespace std;
 
// such a function will not be safe if x is non static
// variable of it
int& fun()
{
    static int x;
    return x;
}
 
// Driver Code
int main()
{
    fun() = 10;
 
    // this line prints 10 as output
    printf(" %d ", fun());
 
    getchar();
    return 0;
}


Output

 10 

Time Complexity : O(1)

Auxiliary Space: O(1)



Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg