naming convention of temp local variables

2019-03-01 06:38发布

What is the standard way to name a temp variable in the local function? let me give you an illustration of what I am doing. I get a pointer to a structure, so I want store one of its members locally to avoid a de-referenced, and then any modification assign back to the pointer.

To be more concrete:

struct  Foo
{
  double m_d;

};


void function (Foo* f)
{
   double tmp=f->m_d;

       /***Other stuff***/

     f->m_d=tmp;
}

I don't like tmp. If I have many of them in a function, they only add a confusion.

Thanks

11条回答
混吃等死
2楼-- · 2019-03-01 07:12

What do you store in the tmp variable? Use that description as a variable name, if it isn’t too long. For three-line functions (swap …) tmp is just fine. For almost everything else, be descriptive.

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-01 07:12

For your information: Code Complete has a chapter decicated to variable naming.

In your example one problem is that the member variable in Foo is not very descriptive to start with, which makes it hard to find a useful name for the placeholder local variable.

For example, I would do something like this:

struct Foo
{
  double mValue; // I don't use underscores here
                 // however, you can do as you please.
                 // Also 'mValue' is just for the sake of example,
                 // you should find a more descriptive name :D

};


void function (Foo* f)
{
   double oldValue = f->mValue;

       /***Other stuff***/

   f->mValue = oldValue;
}
查看更多
叛逆
4楼-- · 2019-03-01 07:14

There are some 'frequently used shorthands', such as i,j and m and n for loops, but if you are going to have many loops in a function, it's probably best to have something more expressively.

I would use the rules for good variable naming for most cases. If you are doing C++, the question I think is 'how am I going to differentiate member variables' instead of local variables.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-03-01 07:14

Do the same thing you would for any other variable: Give it a concise, expressive name. How about using the original name of the member variable you're copying (possibly leaving off the m_)? That's the best way to make the connection between the two explicit.

查看更多
相关推荐>>
6楼-- · 2019-03-01 07:15

My suggestion is to simply incorporate the original variable name, or some other identifier that alerts readers of its intented function.

struct  Foo
{
  double m_d;

};


void function (Foo* f)
{
   double m_d_tmp = f->m_d;

       /***Other stuff***/

     f->m_d = m_d_tmp;
}
查看更多
太酷不给撩
7楼-- · 2019-03-01 07:19

If a more descriptive them can't be thought of, the convention we practice at work is to use the name "my[object]" in lieu of a better name. Above all, make it descriptive so that your code is easier to understand and maintain. Self-documenting code is another benefit of doing this.

查看更多
登录 后发表回答