0

I have union called f defined as

union uf {
  unsigned u;
  float f;
}

I have two functions.

void inner_function(uf& in) {
  //modify in
}

void outer_function(unsigned& val) {
  inner_function(static_cast<uf> (val));
}

can someone please explain me why I am getting "invalid initialization of non-const reference of type 'uf&' from a temporary of type 'uf' error.

So I understand that I can't cast this. So how would someone can fix this issue? I know this works

void outer_function(unsigned& val) {
  uf a; 
  a.u = val;
  inner_function(a);
  val = a.u;
}

anything more efficient?

fromCtoCpp
  • 11
  • 2

1 Answers1

1

The result of a static_cast<T>(x) where T is not a reference type is an rvalue of the given type. You cannot bind a non-const reference to an rvalue, and thus the error.

You could do reinterpret_cast<uf&> to make the compiler happy, but you are probably trying to do something the wrong way, and chances are that you will hit undefined behavior in that piece of code somewhere.

The interesting question would be, how do you think that casting to the union type is going to help you? (that is, what is the original problem that you are trying to solve)

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489