Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5.3节 switch内部的变量定义 #66

Closed
SlothSimon opened this issue Aug 2, 2016 · 3 comments
Closed

5.3节 switch内部的变量定义 #66

SlothSimon opened this issue Aug 2, 2016 · 3 comments

Comments

@SlothSimon
Copy link

这一块给了一个例子,对于其中的一个注释不太理解。

case true:
    string file_name;    //  错误:控制流绕过一个隐式初始化的变量
    int ival = 0;
    int jval;    //  正确:因为jval没有初始化
    break;
case false:
    jval = next_num();
    if (file_name.empty())
        // ...

为什么file_name会隐式初始化而jval不会?是因为string不是内置类型吗?所有的非内置类型都会隐式初始化?
另外,int类型没有初始化而输出时其实会输出0,那这个int类型到底有没有初始化呢?(用的mac上的g++,不知道是不是有影响)
谢谢!

@pezy
Copy link
Member

pezy commented Aug 4, 2016

建议你重新复习一下 3.2 节的 Default Initialization 这一小节.

为什么file_name会隐式初始化而jval不会?

因为 file_name 是 std::string 类型, 而 jvalint.

是因为string不是内置类型吗?

这样说不准确, 首先, string 是一个 class type. 一个 class type 是否可以隐式初始化, 完全取决于该类的设计(这个14, 15 章会细讲). 但可以肯定的是, std::string 允许隐式初始化.

所有的非内置类型都会隐式初始化?

显然不是. 你可以轻松定义一个类型, 而不提供隐式初始化.

int类型没有初始化而输出时其实会输出0,那这个int类型到底有没有初始化呢?

如果你指的是 jval, 那么它的值是未定义的. 可能是任何值, mac 上偏向于是 0, windows 上就不好说了.

@SlothSimon
Copy link
Author

重读这一节+查资料后,对于值初始化和默认初始化又有点想法,看书上的介绍(7.5.3节)感觉值初始化算是默认初始化的一种,但是对于二者的区别还不甚了了。
另外,除了函数体内内置类型的默认初始化后值是未定义外,还有别的情况会导致定义的变量值未定义吗?
非常感谢!

@pezy
Copy link
Member

pezy commented Aug 11, 2016

还有别的情况会导致定义的变量值未定义吗

有, 譬如类的某些成员变量.

class c {
    int i; // 值未定义
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants