It is a pure style question, but, the code is more readable in the first or in the second way? There are rules that talk about it? (I think that the code efficiency is the same, or it isn't?)

有帮助吗?

解决方案

I think you probably mean assignment or initialization rather than allocation. Making this assumption it's generally thought to be better to declare and assign in the same line.

So rather than

int x; // declare
// ... some lines of code
x = y + z; // assign

do

int x = y + z;

This has the advantages of

  • Not having the "wrong" value in x until it is assigned. In some languages the value in x will even be undefined.

  • Associating the declaration with the first use, so it's more readable.

  • Encouraging a style where you declare your variables later, so there is no chance that you will inadvertantly use them before you first initialise them.

There are indeed rules that talk about this: many coding standards specify initializing variables on declaration, and declaring them as late as possible.

In my opinion, this is not primarily about efficiency. For example in compiled languages such as C++, many compilers can and will spot that you haven't used the variable until you assigned it and will only allocate the memory at the point of assignment. However in general, the more you make your intentions clear to your system by programming in the simplest, most parsimonious way, the better your compiler is able to optimize your code. So if, for example, you were a C or Delphi programmer used to the old restriction that all declarations had to be at the top of the function, and decided to interpret "assign at the same time as declare" to try to move all of your assignments up to the top of the function where your declarations were, rather than your declarations down, then you might introduce inefficiencies and quite possibly bugs.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top