user1000
user1000

Reputation: 91

C expression must be a modifiable l-value returning pointer

I'm trying to assign a returned pointer from a function to another pointer. Why can't I? Simple example:

int * foo(int * x)
{
    return x;
}

int main()
{
    int * x = NULL;
    int * y = NULL;
    foo(x) = y;
}

Upvotes: 0

Views: 274

Answers (4)

John Bollinger
John Bollinger

Reputation: 180171

I'm trying to assign a returned pointer from a function to another pointer. Why can't I?

Because functions return values, not objects. Objects have storage which can contain and represent values. Values themselves are are transient and immutable. Even pointer values. Your example is analogous to this:

double bar(void) {
    return 1.0;
}

int main() {
    double y = 0.0;
    bar() = y;
}

The return value of bar() is a value. You cannot assign to it because it is not an object and has no associated storage.

You could do the reverse: assign the return value of bar() to variable y, like so: y = bar(). That's fine because y designates an object (it is the identifier of a variable, the most common kind of object). Expressions that designate objects are called "lvalues", because they can appear on the left side of assignment statements and can also be evaluated to yield values.

Different types, including those with pointer nature, don't really factor in here. Every complete type affords both lvalue and non-lvalue expressions of that type.

You can dereference valid pointer expressions, however, even those that are not themselves lvalues, and such expressions are lvalues. Thus, this variation on your program would be accepted:

int *foo(int *x) {
    return x;
}

int main() {
    int nums[2] = { 42, 7 };
    int *x = &nums[0];
    int *y = &nums[1];

    *foo(x) = *y;
}

The final assignment will set the object to which the return value of foo() points (num[0]) to the value to which y points (num[1]). That is, after that assignment, array nums contains elements {7, 7}.

Upvotes: 2

pmg
pmg

Reputation: 108978

Try this for fun.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *foo(int *x) {
    return x + rand() % 3;
}

int main(void) {
    int x[3] = {0};
    srand(time(0));
    *foo(x) = 42;
    printf("x is {%d, %d, %d}\n", x[0], x[1], x[2]);
    return 0;
}

Upvotes: 2

Gaurav
Gaurav

Reputation: 1600

Because the function returning the pointer should be on right side of the = --> y = foo(x).

Here is a not so simple example to deomnstrate that:

#include<stdio.h>

int *foo(int *x)
{
    return x;
}

int main(void)
{   
    int *x=NULL;
    int *y=NULL;
    int a=9;

    x=&a;

    y=foo(x);
    printf("%d\n",*y);

    return 0;
}

OUTPUT: 9

Upvotes: 0

shirish
shirish

Reputation: 678

The l-value of assignment operator should be a variable and not a value.
You can't use a function since the function returns a value(pass by value in C). So it should be

y = foo(x);

Upvotes: 0

Related Questions