1

Why is the second line of the following code throwing a C error : lvalue required as left operand of assignment

  if (!str_cmp( type, "obj")){
    if ( ((OBJ_DATA*) tar = get_obj_here( NULL, room, target)) == NULL){
      bug("prog_destroy: obj target not found.", 0);
      return;
    }
    else{
      list = (OBJ_DATA*) tar;
      list = list->contains;
    }
  }
jisaacs1207
  • 99
  • 3
  • 13

3 Answers3

2

You cannot cast on the LHS of an assignment. I.e. (OBJ_DATA*) tar is not allowed on the second line.

You can try declaring OBJ_DATA * tar = NULL; then using it as

tar = get_obj_here( NULL, room, target)

or

tar =(OBJ_DATA*) get_obj_here( NULL, room, target)

depending on what get_obj_here() returns.

alk
  • 69,737
  • 10
  • 105
  • 255
gaurav5430
  • 12,934
  • 6
  • 54
  • 111
2

Casting results in a r-value. It can't be done on the left side (l-value) of = operator.

if ( ((OBJ_DATA*) tar = get_obj_here( NULL, room, target)) == NULL)  
        ^
        |
   Remove this data type
haccks
  • 104,019
  • 25
  • 176
  • 264
0

I think that's an error in the code.

According to this question,

You cannot cast the left operand of the assignment operator in C.

And this question (Casting a pointer does not produce an lvalue. Why?) goes into more detail.

The underlying reason is that all these things, including your cast, create a new value. Casting a value to the type it already is, likewise creates a new value, never mind whether pointers to different types have the same representation or not. In some cases, the new value happens to be equal to the old value, but in principle it's a new value, it's not intended to be used as a reference to the old object, and that's why it's an rvalue.

For these to be lvalues, the standard would have to add some special cases that certain operations when used on an lvalue result in a reference to the old object, instead of a new value. AFAIK there's no great demand for those special cases.

Community
  • 1
  • 1