tags:

views:

166

answers:

6

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?

A: 

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).

MarkusQ
+8  A: 

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.

anon
Yeah. Last time I used one, I was using the Win32 API. There was something wrong with the code, and it wasn't me. Probably one of those things that looked like a better idea fifteen years ago.
David Thornley
+1 for nice mantra.
bb
A: 

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.

chaos
+2  A: 

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

Brian Neal
A: 

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.

e.James
A: 

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

Either way, it looks fairly pointless.

Evan Teran