windows BOOL 和 bool 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6420526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:29:54  来源:igfitidea点击:

What is the difference between BOOL and bool?

windowswinapivisual-c++mfc

提问by Umesha MS

In VC++ we have the data type “BOOL” which can assume the value TRUE or FALSE, and we have the data type “bool”, which can assume the value true or false.

在 VC++ 中,我们有数据类型“BOOL”,它可以取值为 TRUE 或 FALSE,我们有数据类型“bool”,它可以取值为 true 或 false。

What is the difference between them and when should each data type be used?

它们之间有什么区别以及应该何时使用每种数据类型?

回答by luvieere

boolis a built-in C++ type while BOOLis a Microsoft specific type that is defined as an int. You can find it in windef.h:

bool是内置的 C++ 类型,而BOOL是 Microsoft 特定类型,定义为int. 您可以在windef.h以下位置找到它:

typedef int                 BOOL;

#ifndef FALSE
#define FALSE               0
#endif

#ifndef TRUE
#define TRUE                1
#endif

The values for a boolare trueand false, whereas for BOOLyou can use any intvalue, though TRUEand FALSEmacros are defined in the windef.hheader.

a 的值booltrueand false,而 forBOOL您可以使用任何int值,但TRUEFALSE宏在windef.h标题中定义。

This means that the sizeofoperator will yield 1 for bool(the standard states, though, that the size of boolis implementation defined), and 4 for BOOL.

这意味着sizeof操作符将产生 1 for bool(尽管标准规定, 的大小bool是实现定义的)和 4 for BOOL

Source: Codeguru article

来源:Codeguru 文章

回答by Ajay

Windows API had this type before boolwas thrown into C++. And that's why it still exits in all Windows function that take BOOL. C doesn't support booldata-type, therefore BOOLhas to stay.

Windows API 在bool被扔进 C++之前就有这种类型。这就是为什么它仍然存在于所有采用 BOOL 的 Windows 函数中。C 不支持bool数据类型,因此BOOL必须保留。

回答by Aamir

To add to what luvieere has said, you can return something other than TRUEor FALSEfrom a function returning a BOOLe.g.,

为了补充 luvieere 所说的,您可以返回除返回 a 的函数之外的其他内容TRUEFALSE从返回BOOL例如的函数中返回的内容,

BOOL myFunc(int a)
{
    if (a < 3) return FALSE;
    else if (a > 3) return TRUE;
    else return 2;
}

And this is possible because a BOOLis essentially an int.

这是可能的,因为 aBOOL本质上是 an int

Please note that this is not advisable as it severely destroys the general readability of code but it is something you can come across and you will be wondering why it is so.

请注意,这是不可取的,因为它严重破坏了代码的一般可读性,但您可能会遇到这种情况,您会想知道为什么会这样。