gpt4 book ai didi

c++ - 工程 bool 比较等于真假,为什么?

转载 作者:IT老高 更新时间:2023-10-28 21:47:45 28 4
gpt4 key购买 nike

下面的例子可以编译,但是输出很奇怪:

#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;
}

输出是:

true
true

有人能解释一下原因吗?

如果重要的话,我使用的是 g++ 4.3.0

最佳答案

在 C++ 标准第 3.9.1 节“基本类型”中找到了这一点(注意神奇的脚注 42):

6. Values of type bool are either true or false. 42)

42) Using a bool value in ways described by this International Standard as ‘‘undefined,’’ such as by examining the value of an uninitialized automatic variable, might cause it to behave as if it is neither true nor false.

这对我来说不是很清楚,但似乎回答了这个问题。

关于c++ - 工程 bool 比较等于真假,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4518951/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com