views:

46

answers:

2

If I have something like:

typedef int MyType;

is it good practice to cast the operands of an operation if I do something like this:

int x = 5;
int y = 6;

MyType a = (MyType)(x + y);

I know that I don't need to do that but wondering if it's better for intent/documentation/readability concerns. Or, should I just do:

MyType a = x + y;

There may be reasons why x and y aren't declared as MyType but the sum of them could be used as an argument to a function that takes MyType, for example.

+1  A: 

I wouldn't use a cast. It's unnecessary, looks messy, makes the code harder for a person to parse, and obscures the intent of the code.

If you use typedefs consistently (i.e., if you declare x and y as MyType objects as well), you shouldn't have too much of a problem with this.

James McNellis
A: 

The cast is unnecessary, and kinda ugly; if I were maintaining this code I'd yank it out in passing the the first time I read through that file on general principles. So no, it won't do anything bad - it's just indicating what is going to happen to the value of x + y anyways - but it clutters the line and the declaration of a as MyType already provides all the documentation that line needs.

In general, I feel you should try to explicitly cast things as little as possible; when you see a cast in code it should be an indicator that something noteworthy is happening, not simply that a variable's type is going to be changed during execution.

I'm not sure what you mean by "noteworthy" and not simply a variable's type is going to be changed.
mesorismo