变量要使用前定义
C要在作用域开始处定义,编译器在创建一个块时,能给所有变量分配空间
C代码进入作用域开头,所有变量都定义了
写新变量又要回到作用域的开头,导致混乱,因为上下文无关
C++允许在作用域任何地方定义,使用之前定义就好。
定义变量时同时初始化避免错误,让代码编写更容易,减少作用域跳转带来的问题
C要在作用域开始处定义,编译器在创建一个块时,能给所有变量分配空间
C代码进入作用域开头,所有变量都定义了
写新变量又要回到作用域的开头,导致混乱,因为上下文无关
C++允许在作用域任何地方定义,使用之前定义就好。
定义变量时同时初始化避免错误,让代码编写更容易,减少作用域跳转带来的问题
上下文定义变量,代码更容易理解
//: C03:OnTheFly.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// On-the-fly variable definitions
#include <iostream>
using namespace std;
int main() {
//..
{ // Begin a new scope
int q = 0; // C requires definitions here
//..
// Define at point of use:
for(int i = 0; i < 100; i++) {
q++; // q comes from a larger scope
// Definition at the end of the scope:
int p = 12;
}
int p = 1; // A different p
} // End scope containing q & outer p
cout << "Type characters:" << endl;
while(char c = cin.get() != 'q') {
cout << c << " wasn't it" << endl;
if(char x = c == 'a' || c == 'b')
cout << "You typed a or b" << endl;
else
cout << "You typed " << x << endl;
}
cout << "Type A, B, or C" << endl;
switch(int i = cin.get()) {
case 'A': cout << "Snap" << endl; break;
case 'B': cout << "Crackle" << endl; break;
case 'C': cout << "Pop" << endl; break;
default: cout << "Not A, B or C!" << endl;
}
} ///:~
最内层作用域,p在作用域结束前定义,是一个毫无意义的变量
for循环的i,i的作用域就是循环控制的表达式的作用域。
输出
ype characters:
a
wasn't it
You typed
wasn't it
You typed
按q退出