创建变量并调用函数同时进行

huangapple go评论59阅读模式
英文:

Calling function and creating variable in one go

问题

我可能想得太多了,已经断断续续编码了几个月,但现在在寻找关于一些非常简单的最佳实践建议。
问题:像这样做是否被看作不好的做法?

uint8_t dotPos = GetDotPos(&buffer[0], len);

还是更好的做法(通常在示例中看到)是这样的:

uint8_t dotPos = 0;
dotPos = GetDotPos(&buffer[0], len);

还是没有偏好?

英文:

I'm probably overthinking this, and have been coding on and off a few months but am looking for best practice advice on something very simple.
Question: Is it frowned upon on do something like this?

uint8_t dotPos = GetDotPos(&buffer[0], len);

or is it better practice (as is often seen in examples) to do this:

uint8_t dotPos = 0;
dotPos = GetDotPos(&buffer[0], len);

Or is there no preference?

答案1

得分: 3

const uint8_t dotPos = GetDotPos(&buffer[0], len);

这是更好的做法。变量的声明和初始化应该尽可能靠近,以提高代码的可读性。此外,如果变量不会改变,应将其设置为const。遵循这种约定极大地简化了我们脑海中代码的流程分析。

来自https://google.github.io/styleguide/cppguide.html#Local_Variables:

> 将函数的变量放在可能的最窄作用域内,并在声明时初始化变量。
>
> int i;
> i = f(); // 不好 -- 初始化与声明分开。
>
> int i = f(); // 好 -- 声明时已初始化。

还可以参考https://wiki.c2.com/?DeclareVariablesAtFirstUse。


<details>
<summary>英文:</summary>

    const uint8_t dotPos = GetDotPos(&amp;buffer[0], len);

is the better practice. Variable declaration and initialization should be close together for code readability. Additionally, if the variable is not changed, set it to `const`. Following this convention greatly simplifies flow analysis of the code in our heads.

From https://google.github.io/styleguide/cppguide.html#Local_Variables :

&gt; Place a function&#39;s variables in the narrowest scope possible, and initialize variables in the declaration.
&gt;
&gt;     int i;
&gt;     i = f();      // Bad -- initialization separate from declaration.
&gt;
&gt;     int i = f();  // Good -- declaration has initialization.

Also https://wiki.c2.com/?DeclareVariablesAtFirstUse . 

</details>



# 答案2
**得分**: 2

&gt; _&ldquo;进行这样的操作是否不受欢迎...&rdquo;_  
&gt; _&ldquo;还是最好的做法是...&rdquo;_  
&gt; _&ldquo;还是没有偏好吗?&rdquo;_  

你的问题的措辞暗示你可能已经有一个自然的偏好。试一试。尽管对于语法和语义的新信息持开放态度是好的,但要注意你会从哪里或从谁那里接受这些信息。通常,程序员,尽管出于善意,也会建议在形成适合特定观点习惯时使用习惯性结构。但要小心接受想法,特别是当它们范围狭窄,并且使用过多绝对语言时。光滑呈现但过于学究式的命令应该在确定之前加以审查。

你的问题涉及一个非常特定的场景,但要考虑你可能会遇到的其他情况,以充分解决何时/如何创建和初始化变量的问题...

- 变量是否也会用作函数的参数?
- 是否需要变量具有全局范围?
- 还是打算具有局部(自动)范围?
- 变量是否将在多线程环境中使用?

这些情况将影响你如何创建、初始化和可能维护变量的完整性,因此可能会再次考虑新信息。

<details>
<summary>英文:</summary>

&gt; _&quot;Is it frowned upon on do something like...&quot;_  
&gt; _&quot;or is it better practice...&quot;_  
&gt; _&quot;Or is there no preference?&quot;_

The phrasing of your question suggests you may already have a natural preference. Try it out.    
Although being open to learning new information regarding syntax and semantics is good, be careful from where, or whom you will accept that information.  Often programmers,  albeit with good intentions will suggest _[idiomatic constructs](https://en.wikipedia.org/wiki/Programming_idiom)_ when teaching (or persuading) another to form habits in a manner suitable to a particular point of view. However be careful when accepting ideas, in particular when they are narrowly scoped, and use language with too many absolutes.  (_always_ do it this way, _never_ use ... )  Smoothly presented but overly pedantic mandates should be scrutinized before settling on them.

Your question addresses a very specific scenario, but consider other scenarios you are likely to encounter to fully address how/when to create and initialize variables... 

  - will variable also be _[used as an argument](https://stackoverflow.com/questions/61066606/is-undefined-behavior-to-declare-a-variable-while-passing-by-reference)_ to the function?
  - Is the variable required to have _[global](https://stackoverflow.com/questions/176118/when-is-it-ok-to-use-a-global-variable-in-c)_ scope?
  - or, is it intended to have local (automatic) scope?
  - will variable be used in a threaded environment?  

Each of these will factor into how you create, initialize, and perhaps maintain the integrity of your variable, thus will likely cause you to once again consider new information.  



</details>



# 答案3
**得分**: 0

两者都被广泛使用。一些人可能更喜欢其中之一,这完全是一种品味问题。一些人可能会争论后者允许在函数顶部声明所有函数变量,这可以被认为更清晰。

<details>
<summary>英文:</summary>

Both are extensively used. Some people may prefer one or the other and it&#39;s totally a matter of taste. Some people may argue that the later allow to declare all function variable on the top of the function which can be considered cleaner.

</details>



# 答案4
**得分**: 0

通常编译器会进行代码优化,如常量折叠和常量传播,因此赋值不应影响性能。

由您决定您偏好的方法,或者如果您的组织指定了特定的方法。

<details>
<summary>英文:</summary>

Usually the compiler does code optimization like Constant Folding and Constant Propagation so the assignment should not affect performance.

It is up to you which method you prefer or if your organization specifies a certain method.


</details>



# 答案5
**得分**: 0

这取决于你想要的 "i" 的作用域。
如果你在循环或条件中设置 "i" 并计划在外部使用它,那么你需要在循环或作用域 {} 之前声明它,否则编译器在引用相同变量但没有声明时会报错。

否则,声明和赋值的单个语句是正确且最佳的。

此外,如果变量是指向内存位置的指针,那么最佳实践是在赋值之前调用 memset/calloc 来清除该位置,因为你不知道指向的位置中可能存在什么。

<details>
<summary>英文:</summary>

It depends on the scope of &quot;i&quot; that you want. 
If you are setting &quot;i&quot; in a loop or a condition and plan to use it outside then you need to have the declaration prior to it and outside of the loop/scope {}, else the compiler will complain as soon as you reference the same variable without a declaration. 

Otherwise the single statement for declaration and assignment is correct and optimal. 

Also if the variable is a pointer to a memory location then you definitely need to call a memset/calloc to clear the location prior to assignment as a best practice because you dont know what is lurking in the pointed location. 

</details>



huangapple
  • 本文由 发表于 2023年7月3日 19:38:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定