0

Is it bad practice to initialize and do arithmetic within a variable? i.e say I have multiple rooms of different area dimensions that I must find the area of:

(example in feet)

double room_area1 = 9.5 * 6.8;
double room_area2 = 9.1 * 6.2;
double room_area3 = 10.0 * 7.1; 

Or is it best to do:

double room_area1 = 9.5;
room_area1 = room_area1 * 6.8;

Is there any disparity between the two ways here or is it the same thing and just a matter of style?

Ajay
  • 18,086
  • 12
  • 59
  • 105
wilbomc
  • 183
  • 3
  • 13

3 Answers3

2

First involves only one operation: Initialization,
While second involves two operations: Initialization + Assignment.

For an intrinsic data type like double the overhead is negligible but for user defined data types second is detrimental to performance(How much? Profiling should tell that).

So in general it is better practice to use First because:

  • It is guaranteed to be atleast as fast if not faster than Second
  • It is more readable.
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

The first way is better. Reason: it's more readable.

While it is correct, that these constructions are semantically different, for simple types the compiler will almost certainly optimize the second case to be like the first case, and generate the same machine code, storing a constant (calculated at compile-time) into room_area1.

Eugene Ryabtsev
  • 2,232
  • 1
  • 23
  • 37
1

There's nothing wrong with the first examples. In fact it's better that way because you can declare the variable const.

user1610015
  • 6,561
  • 2
  • 15
  • 18