I’m studying D language and simultaneously doing comparison to C and C++ languages.It works fine both dmd and gdc compilers,but when I tested on gcc compiler,I found a thing that looks like bug of GCC compiler,the default initializer of boolean type instead of 0/false see the following code:
C++ code
#include <iostream>
using namespace std;
int main()
{
bool b;
cout << b << endl;
return 0;
}
G++ compiler(gcc version 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 code(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 compiler
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 compiler
tcc -Wall foo.c
./a.out
0
clang compiler
clang -Wall -pedantic foo.c
./a.out
0
Can someone explain the gcc behavior?
Default initialization in C++ for basic types means “uninitialized”. That is, any value can be there. You got 64 because that just happened to be in that memory location.
If you want to do value initialization, then you need to use
bool():Value initialization effectively means initializing basic types to zero.
C++11 makes this rather cleaner: