示例波纹管编译,但输出相当奇怪:
#include <iostream>
#include <cstring>
struct A
{
int a;
char b;
bool c;
};
int main()
{
A v;
std::memset( &v, 0xff, sizeof(v) );
std::cout << std::boolalpha << ( true == v.c ) << std::endl;
std::cout << std::boolalpha << ( false == v.c ) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
true
true
Run Code Online (Sandbox Code Playgroud)
有人能解释为什么吗?
如果重要,我使用的是g ++ 4.3.0
我已经阅读了该问题的答案:为什么 c++ 中的 char 和 bool 的大小相同?并做了一个实验来确定内存中分配的字节大小 a_Bool和 a bool(我知道这bool是一个_Boolin的宏,stdbool.h但为了完整起见,我也使用了它)在 C 中的bool对象,以及在我的实现中的 C++ 中的对象Linux Ubuntu 12.4:
对于 C:
#include <stdio.h>
#include <stdbool.h> // for "bool" macro.
int main()
{
_Bool bin1 = 1;
bool bin2 = 1; // just for the sake of completeness; bool is a macro for _Bool.
printf("the size of bin1 in bytes is: %lu \n",(sizeof(bin1)));
printf("the size of bin2 in bytes is: %lu …Run Code Online (Sandbox Code Playgroud) 有许多声称使用未初始化的变量会调用未定义的行为(UB).
仔细阅读文档,我无法验证该声明,因此我想要一个令人信服的论据,为C和C++澄清这一点.
我期望两者都有相同的语义,但我准备对微妙或不那么微妙的差异感到惊讶.
使用未初始化变量开始的一些示例.请根据需要添加其他人,以解释他们未涵盖的任何角落案例.
void test1() {
int x;
printf("%d", x);
}
void test2() {
int x;
for(int i = 0; i < CHAR_BIT * sizeof x)
x = x << 1;
printf("%d", x);
}
void test3() {
unsigned x;
printf("%u", x); /* was format "%d" */
}
void test4() {
unsigned x;
for(int i = 0; i < CHAR_BIT * sizeof x)
x = x << 1;
printf("%u", x); /* was format "%d" */
}
Run Code Online (Sandbox Code Playgroud)