Olusegun Ode
Olusegun Ode

Reputation: 11

Using rvalues with the & operator

I've been struggling to understand the C code below:

struct s {
        char m1;
        char m2;
};

int  main()
{
    /* This will print 1 */
    printf("%d\n", &((struct s*)0)->m2);

}

The portion below seems to behave a bit confusing under slight modification:

&((struct s*)0)->m2

On compiling, and running the initial code,I get an answer of 1, which I expect to get.

I modify the code by replacing &((struct s*)0)->m2 with &((struct s*)0), and then I get an error saying that, "lvalue required as unary '&' operand".

QUESTION: In the original code portion, &((struct s*)0)->m2, wasn't the argument to & an rvalue? If so, why did it reach compilation success then but not in the case of the modification &((struct s*)0)?

Upvotes: 1

Views: 53

Answers (1)

dbush
dbush

Reputation: 223739

In this case:

 &((struct s*)0)

The operand to & is the result of a cast which is always an rvalue. While in this case:

&((struct s*)0)->m2

The operand to & is the result of the -> operator which is an lvalue, specifically the named field. Also note that this expression results in undefined behavior because a NULL pointer value is being dereferenced via the -> operator.

Upvotes: 2

Related Questions