C程序员的C++指导书(4)
变量可以在代码中的任意位置声明。
1 using namespace std; 2 #include <iostream> 3 4 int main () 5 { 6 double a; 7 8 cout << "Hello, this is a test program." << endl; 9 10 cout << "Type parameter a: "; 11 cin >> a; 12 13 a = (a + 1) / 2; 14 15 double c; 16 17 c = a * 5 + 1; 18 19 cout << "c contains : " << c << endl; 20 21 int i, j; 22 23 i = 0; 24 j = i + 1; 25 26 cout << "j contains : " << j << endl; 27 28 return 0; 29 }
可以用这个特性让代码可读性更好。像C一样,在花括号里面的变量的作用区域即为花括号内部。
1 using namespace std; 2 #include <iostream> 3 4 int main () 5 { 6 double a; 7 8 cout << "Type a number: "; 9 cin >> a; 10 11 { 12 int a = 1; 13 a = a * 10 + 4; 14 cout << "Local number: " << a << endl; 15 } 16 17 cout << "You typed: " << a << endl; 18 19 return 0; 20 }
这不都跟C一样么??