设为首页 加入收藏

TOP

2.2 Variables (4)
2013-10-07 16:15:10 来源: 作者: 【 】 浏览:64
Tags:2.2 Variables

Default Initialization

When we define a variable without an initializer, the variable is default initialized. Such variables are given the “default” value. What that default value is depends on the type of the variable and may also depend on where the variable is defined.

The value of an object of built-in type that is not explicitly initialized depends on where it is defined. Variables defined outside any function body are initialized to zero. With one exception, which we cover in § 6.1.1 (p. 205), variables of built-in type defined inside a function are uninitialized. The value of an uninitialized variable of built-in type is undefined (§ 2.1.2, p. 36). It is an error to copy or otherwise try to access the value of a variable whose value is undefined.

Each class controls how we initialize objects of that class type. In particular, it is up to the class whether we can define objects of that type without an initializer. If we can, the class determines what value the resulting object will have.

Most classes let us define objects without explicit initializers. Such classes supply an appropriate default value for us. For example, as we’ve just seen, the library string class says that if we do not supply an initializer, then the resulting string is the empty string:

  1. std::string empty; // empty implicitly initialized to the empty string   
  2. Sales_item item; // default-initialized Sales_item object  

Some classes require that every object be explicitly initialized. The compiler will complain if we try to create an object of such a class with no initializer.

Uninitialized objects of built-in type defined inside a function body have undefined value. Objects of class type that we do not explicitly initialize have a value that is defined by the class.

EXERCISES SECTION 2.2.1

Exercise 2.9: Explain the following definitions. For those that are illegal, explain what’s wrong and how to correct it.

(a) std::cin >> int input_value; (b) int i = { 3.14 };

(c) double salary = wage = 9999.99; (d) int i = 3.14;

Exercise 2.10: What are the initial values, if any, of each of the following variables

  1. std::string global_str;   
  2. int global_int;   
  3. int main()   
  4. {   
  5. int local_int;   
  6. std::string local_str;   

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.2 Variables (3) 下一篇1.3 AWord about Comments (2)

评论

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

·数据库:推荐几款 Re (2025-12-25 12:17:11)
·如何最简单、通俗地 (2025-12-25 12:17:09)
·什么是Redis?为什么 (2025-12-25 12:17:06)
·对于一个想入坑Linux (2025-12-25 11:49:07)
·Linux 怎么读? (2025-12-25 11:49:04)