这使得它似乎有点更清楚,价值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:
老年编译器强制用户定义函数中的所有变量的函数的顶部的功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}
这种风格现在已经过时。编译器不需要在函数的顶部定义所有变量。适当的+ +的风格是将变量定义为可能的变量,尽可能靠近第一次使用这个变量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}