我正在学习 D 语言,同时与 C 和 C++ 语言进行比较。它在 dmd 和 gdc 编译器上都工作正常,但是当我在 gcc 编译器上测试时,我发现了一个看起来像 GCC 编译器的错误,默认 bool 类型的初始值设定项而不是 0/false 请参见以下代码:
C++代码
#include <iostream>
using namespace std;
int main()
{
bool b;
cout << b << endl;
return 0;
}
G++编译器(gcc版本4.4.3(Ubuntu 4.4.3-4ubuntu5.1):
g++ -Wall -pedantic test.cpp
test.cpp: In function ‘int main()’: test.cpp:7: warning: ‘b’ is used
uninitialized in this function
./a.out 64
C 代码(foo.c):
#include <stdio.h>
#include <stdbool.h>
#define bool _Bool
int main(int argc, char * args[])
{
bool b;
printf("%d\n", b);
return 0;
}
gcc 编译器
gcc-4.6 -Wall -pedantic a.c
foo.c: In function ‘main’:
foo.c:9:8: warning: ‘b’ is used uninitialized in this function [-Wuninitialized]
./a.out
64
tcc 编译器
tcc -Wall foo.c
./a.out
0
clang 编译器
clang -Wall -pedantic foo.c
./a.out
0
有人可以解释 gcc 的行为吗?
最佳答案
如您的警告消息所示,您在使用局部变量之前并未对其进行初始化,因此它们的内容将是未定义的。
关于c++ - GCC 编译器上 bool 类型的 C 和 C++ 语言的默认初始值设定项是 64 而不是 0。这是编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10307948/