这使得它似乎有点更清楚,价值5是只被分配到变量B。
Because defining multiple variables on a single line AND initializing them is a recipe for mistakes, we recommend that you only define multiple variables on a line if you’re not initializing any of them.
因为定义多个变量在一个单一的线和初始化是一方的错误,我们建议您只定义多个变量对线如果你没有初始化任何人。
Rule: Avoid defining multiple variables on a single line if initializing any of them.
规则:避免定义多个变量在一个单一的线如果初始化任何人。
Where to define variables
定义变量的地方
Older C compilers forced users to define all of the variables in a function at the top of the function:
老年编译器强制用户定义函数中的所有变量的函数的顶部的功能:
int main()
{
// all variable up top
int x;
int y;
// then code
using namespace std;
cout << "Enter a number: ";
cin >> x;
cout << "Enter another number: ";
cin >> y;
cout << "The sum is: " << x + y << endl;
return 0;
}这种风格现在已经过时。C++编译器不需要所有的变量都是在函数上定义。适当的C++风格定义的变量,变量的第一个接近的使用可能:
int main()
{
using namespace std;
cout << "Enter a number: ";
int x; // we need x on the next line, so we'll declare it here, as close to its first use as possible.
cin >> x; // first use of x
cout << "Enter another number: ";
int y; // we don't need y until now, so it gets declared here
cin >> y; // first use of y
cout << "The sum is: " << x + y << endl;
return 0;
}这有相当多的优势。
First, variables that are defined only when needed are given context by the statements around them. If x were defined at the top of the function, we would have no idea what it was used for until we scanned the function and found where it was used. Defining x amongst a bunch of input/output statements helps make it obvious that this variable is being used for input and/or output.
首先,只有在需要时才定义的变量是在它们的语句中给出的。如果被定义在功能的顶部,我们将不知道它是什么,直到我们扫描的功能,并发现它被使用。定义一堆输入/输出语句之间的定义有助于使其明显的是,这个变量被用于输入和/或输出。
Second, defining a variable only where it is needed tells us that this variable does not affect anything above it, making our program easier to understand and requiring less scrolling.
其次,定义一个变量,只有在它的需要告诉我们,这个变量不影响上面的任何东西,使我们的程序更容易理解,需要较少的滚动。
Finally, it reduces the likelihood of inadvertently leaving a variable uninitialized, because we can define and then immediately initialize it with the value we want it to have.
最后,它减少了无意中留下一个变量未初始化的可能性,因为我们可以定义然后立即初始化它的价值我们要有。
Rule: Define variables as close to their first use as possible.
规则:尽可能靠近他们的第一次使用定义变量。

被折叠的 条评论
为什么被折叠?



