mikeyk
mikeyk

Reputation: 73

Why would you cast the lhs of an assignment?

I came across some code that boils down to the following:

enum BAR { /* enum values omitted */ }

class Foo{
public:
  void set(const BAR& bar);
private:
  uint32_t bits;
};

void Foo::set(const BAR& bar)
{
 (uint32_t&)bits = bits | bar;
}

I don't understand the point of the c-style cast in the assignment in Foo::set. Why would you cast the lhs of an assignment? Am I crazy, or does this have a purpose?

Upvotes: 6

Views: 629

Answers (6)

Evan Teran
Evan Teran

Reputation: 90422

I'm not sure this is legal. a cast is not an lvalue...

Either way, it looks fairly pointless.

Upvotes: 0

James Eichele
James Eichele

Reputation: 119144

I can't say for sure without knowing the background, but it looks like someone may have taken some existing C code and wrapped it in a C++ class. The cast may be a leftover from the c code.

Upvotes: 0

Brian Neal
Brian Neal

Reputation: 32389

I agree with Neil Butterworth, the cast in this case isn't necessary and it is a definite "code smell".

Upvotes: 2

chaos
chaos

Reputation: 124297

It does nothing at all, as far as I can tell, even if BAR is defined with values outside the uint32 range. Looks like noise to me.

Upvotes: 0

anon
anon

Reputation:

In this case, I can't see any reason for the cast, as the thing being cast is of the same type as the cast. In general, it could be used to force a particular assignement operator to be used.

I will now repeat my mantra: If your code contains casts, there is probably something wrong with the code or the design and you should examine both with a view to removing the cast.

Upvotes: 8

MarkusQ
MarkusQ

Reputation: 21950

If you only want to permit certain value to be assigned (e.g., the checking on the assignment is done as if to variable typed as per the cast, instead of just letting anything go through as if you widened the rhs).

Upvotes: -1

Related Questions