GCC 编译器对类型转换做了什么?为什么 mac 和 linux 上的输出不同?
What does GCC compiler do to type conversion? Why the output on mac and linux are different?
我在一个作用域中对变量b(作用域外的声明)做了类型转换,给b赋了一个新的val,当作用域结束时,b的val好像是错误的。
这发生在我的 macbook 上,gcc 的版本是 gcc-8 (Homebrew GCC 8.3.0) 8.3.0。我在 gcc 版本为 5.4.0 的 linux 笔记本电脑上尝试了相同的代码,代码运行良好。
std::vector<int> a = {1,2,3,4};
int b;
{
size_t i = 0, b = a[i];
//this time type of b is size_t
++i;
b = a[i];
}
std::cout << "b = " << b << std::endl;
在我的 mac 上,结果是 b = 0
在 Ubuntu 16 上,结果是 b = 1
两个版本的 gcc 在类型转换上有什么区别?
或者这是一个错误?
您没有进行任何类型转换,您正在范围内创建 second b
,由于它具有相同的名称,shadows the outer b
. This means that you're assigning something to the inner b
and leaving the outer b
untouched. Once the scope ends (at the closing curly brace), you're left with the (uninitialized) outer b
, and printing it invokes undefined behavior,这正是您正在经历的。
这段代码在语义上是等价的,可能会更好地显示实际发生的情况:
vector<int> a = {1,2,3,4};
int outer_b;
{
size_t i = 0, inner_b = a[i];
//this time type of b is size_t
++i;
inner_b = a[i];
}
cout << "b = " << outer_b << endl;
我在一个作用域中对变量b(作用域外的声明)做了类型转换,给b赋了一个新的val,当作用域结束时,b的val好像是错误的。
这发生在我的 macbook 上,gcc 的版本是 gcc-8 (Homebrew GCC 8.3.0) 8.3.0。我在 gcc 版本为 5.4.0 的 linux 笔记本电脑上尝试了相同的代码,代码运行良好。
std::vector<int> a = {1,2,3,4};
int b;
{
size_t i = 0, b = a[i];
//this time type of b is size_t
++i;
b = a[i];
}
std::cout << "b = " << b << std::endl;
在我的 mac 上,结果是 b = 0
在 Ubuntu 16 上,结果是 b = 1
两个版本的 gcc 在类型转换上有什么区别?
或者这是一个错误?
您没有进行任何类型转换,您正在范围内创建 second b
,由于它具有相同的名称,shadows the outer b
. This means that you're assigning something to the inner b
and leaving the outer b
untouched. Once the scope ends (at the closing curly brace), you're left with the (uninitialized) outer b
, and printing it invokes undefined behavior,这正是您正在经历的。
这段代码在语义上是等价的,可能会更好地显示实际发生的情况:
vector<int> a = {1,2,3,4};
int outer_b;
{
size_t i = 0, inner_b = a[i];
//this time type of b is size_t
++i;
inner_b = a[i];
}
cout << "b = " << outer_b << endl;