设为首页 加入收藏

TOP

2.3.7 Define Variables Where They Are Used
2013-10-07 15:22:40 来源: 作者: 【 】 浏览:68
Tags:2.3.7 Define Variables Where They Are Used

In general, variable definitions or declarations can be placed anywhere within the program that a statement is allowed. A variablemust be declared or defined before it is used.

It is usually a good idea to define an object near the point at which the object is first used.

Defining an object where the object is first used improves readability. The reader does not have to go back to the beginning of a section of code to find the definition of a particular variable. Moreover, it is often easier to give the variable a useful initial value when the variable is defined close to where it is first used.

One constraint on placing declarations is that variables are accessible from the point of their definition until the end of the enclosing block. A variable must be defined in or before the outermost scope in which the variable will be used.

EXERCISES SECTION 2.3.6

Exercise 2.19: What is the value of j in the following program

  1. int i = 42;  
  2. int main()  
  3. {  
  4. int i = 100;  
  5. int j = i;  
  6. // . . .  

Exercise 2.20: Given the following program fragment, what values are printed

  1. int i = 100, sum = 0;  
  2. for (int i = 0; i != 10; ++i)  
  3. sum += i;  
  4. std::cout << i << " " << sum << std::endl; 

Exercise 2.21: Is the following program legal

  1. int sum = 0;  
  2. for (int i = 0; i != 10; ++i)  
  3. sum += i;  
  4. std::cout << "Sum from 0 to " << i  
  5. << " is " << sum << std::endl; 
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.3.1 Using bitset Objects or I.. 下一篇5.11 The new and delete Express..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: