Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function ever be on the left side of an assignment operator?

I don't know what use case it might be. I was just wondering if a function would ever appear on the left side of the assignment in C/C++. Just as an example, of course it is wrong, swap(x,y) = 100;

like image 384
Abhyas29 Avatar asked Nov 19 '25 10:11

Abhyas29


2 Answers

It seems that you can do that using references. In C++, that is, there are no references in C.

#include <iostream>

int a = 0;

int& swap(int x, int y) {
    return a;
}

int main()
{
    int x = 0, y = 0;
    swap(x, y) = 100;
    std::cout << "a is " << a << std::endl;
    return 0;
}
like image 111
Blaze Avatar answered Nov 22 '25 00:11

Blaze


C 2018 6.5.16 2 says:

An assignment operator shall have a modifiable lvalue as its left operand.

An lvalue is an expression that may designate an object (such as a name of an object or an *p expression where * is applied to a pointer to an object`). In C, function-call expressions are not lvalues.

like image 36
Eric Postpischil Avatar answered Nov 22 '25 00:11

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!