简体   繁体   English

默认值C ++ 11,编译器到编译器

[英]Default Values C++11, compiler to compiler

Question 1: 问题1:

How can you tell the default value of a variable? 您如何知道变量的默认值? That is (if my vocabulary is wrong) the value of a variables before it is assigned? 那是(如果我的词汇错误)在分配变量之前的值?

Question 2: 问题2:

How does this differ between compilers? 编译器之间有何不同?

Question 3: 问题3:

Is there a better way to default values? 有更好的默认值方法吗?

Question 4: 问题4:

And finally, are there other exceptions to this rule? 最后,此规则还有其他例外吗?

Example code: 示例代码:

bool foolean;
int fintoo;
double fooble;
char charafoo;

What would these be by default compiler to compiler? 默认情况下,这些编译器将是什么?

In all versions of C++, all the variables in your question will be zero-initialized (statically) if they're declared at namespace scope. 在C ++的所有版本中,如果您在问题中的所有变量都在命名空间范围内声明,则将被零初始化(静态)。 In all other cases, they will have garbage values if left uninitialized. 在所有其他情况下,如果不进行初始化,它们将具有垃圾值。

Note that a garbage value is anything which is at the memory location where the variable is defined — it is just a pattern of 0s and 1s. 请注意,垃圾值是定义变量的内存位置中的任何值,它只是0和1的模式。 Such values shouldn't be read by your program, else your code will invoke undefined behaviour . 程序不应读取此类值,否则您的代码将调用未定义的行为

In C++11, if you write these as local variables (or namespace variables): 在C ++ 11中,如果将它们写为局部变量(或名称空间变量):

bool foolean {};
int fintoo {};
double fooble {};
char charafoo {};

They're default-initialized which means zero in this case (as they are built-types). 它们是默认初始化的,在这种情况下意味着为零(因为它们是内置类型)。

If a variable is automatic (that is, a non- static variable local to a function, or a member thereof), there is no default. 如果变量是自动的(即函数或其成员局部的非static变量),则没有默认值。 From pratical perspective, the variable is allocated on stack, and what's there on the stack (probably leftover from a previous function call) will become the value of the variable. 从实际的角度来看,变量是在堆栈上分配的,堆栈上的内容(可能是上一个函数调用留下的内容)将成为变量的值。

Also, some compilers add code to initialize the stack frame to a well-known value in debug mode. 此外,某些编译器会添加代码以在调试模式下将堆栈帧初始化为一个众所周知的值。 That lets you easily see that a variable hasn't been initialized while debugging. 这样一来,您可以轻松地看到调试时尚未初始化变量。

If a variable is static (declared in namespace scope, or with the static keyword in a function), the default is zero. 如果变量是静态的(在名称空间范围中声明,或者在函数中使用static关键字声明),则默认值为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM