When having a class:

class X   
{   int data_;
   void f()
     {     
//shall I cache var data_? by doing
     int cached = data_ 
    //and instead of this:
     if (data_ >= 0 && data_ < 1000 || data_ < 0 && data_ > -1000)//first version
       {
       //do something    
   }     else
       {
       //do somegthing else 
      }    
 // have this:
     if (cached >= 0 && cached < 1000 || cached < 0 && cached > -1000)//second version
     // in my opinion this is bad code
       {
       //do something
       }  
   else 
      { 
      //do somegthing else 
      } 
    }
   };

Please see comments in code.
I'm asking this question because my accomplice from university states that this kind of code (line 1) is just a bad code. I think that he's talking rubbish but I'm very interested in your opinion on this subject.
Thank you.

>>Please see comments in code.

Impossible. The code you posted is just formatted too awful. And the code tags are wrong.

[code=cplusplus] // your code here

[/code]

For those of you who like newlines in your code, I present the following:

class X 
{ 
  int data_;
  void f() 
  { //shall I cache var data_? by doing 
    int cached = data_ 
    //and instead of this: 
    if (data_ >= 0 && data_ < 1000 || data_ < 0 && data_ > -1000)//first version 
    { //do something 
    } 
    else 
    { //do somegthing else 
    } 
    // have this: 
    if (cached >= 0 && cached < 1000 || cached < 0 && cached > -1000)//second version in my opinion this is bad code 
    { //do something
    } 
    else 
    { //do somegthing else
    } 
  } 
};

Thank you -- at least that is readable. :)

I see no reason for the use of variable cashed, at least not in the code you have posted. There are cases where it may be necessary to save the value of a vairable before changing it. So the validity of the two if statements may depend on the value of cashed and data_. It all depends on the rest of that function.

Truthfully, that gives absolutely no advantage, bloats code, makes it hard to read, and is probably slower( although not noticeably ). And as your friend suggest, and your ego denied, its just bad coding. Drop this like a bad habit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.