C中的布尔值 [英] Boolean in C
问题描述
Hello All,
我在C中编写代码,我必须使用布尔数据类型。我正在做 -
typedef int flag;
#define FALSE 0
#define TRUE 1
void main()
{
:
:
flag =!flag;
}
是否flag =!flag等于flag = FALSE?请告诉我。
谢谢。
Hello All,
I am writing a code in C where I have to use the Boolean data type. I am doing -
typedef int flag;
#define FALSE 0
#define TRUE 1
void main()
{
:
:
flag = !flag;
}
Does "flag = !flag" is equal to "flag = FALSE"? Please let me know.
Thanks you.
推荐答案
关于在C中制作自己的Bool类型的一些注意事项。
A few caveats about making your own Bool type in C.
- C99对布尔类型具有内在支持。请参阅< stdbool.h>。
- 如果您不使用C99,则模拟< stdbool.h>可能会有所帮助。在C89中,以便您的软件将来可以轻松移植到C99。
- 最好使用带有布尔变量的谓词逻辑... if(isReady)...而不是显式比较布尔常量。 .. if(isReady == FALSE)。这是因为false(0)有一个值,但是true值为true(所有非零值)。布尔变量可以比较不等于特定值TRUE,但仍然被认为是非假的。
感叹号是逻辑NOT运算符。它反转了操作数的逻辑意义(true变为false; false变为true)。但是,如上所述,除非您选择编译器在将逻辑表达式求值为true时分配的值,否则!FALSE可能无法与您的TRUE常量进行比较。该值保证为1;但是如果你不想负责记住它,那么这样做:#define TRUE(!FALSE)。
The exclamation mark is the logical NOT operator. It inverts the logical sense of the operand (true becomes false; false becomes true). However, as noted above, !FALSE may not compare equal to your TRUE constant unless you chose the value the compiler assigns when it evaluates a logical expression to be true. That value is guaranteed to be "1"; but if you don''t want to be responsible for remembering that then do this: #define TRUE (!FALSE).
@donbock
谢谢你的快速回复。
我试图在C中编写一个函数,如果二叉树中有偶数个节点则返回true(1),否则返回false (0)。我附上以下代码供您参考。请告诉我它是否正确。
#include< stdio.h>
#include< stdbool.h>
bool flag = true;
int is_even_node(tree_ptr p)
{
if(p == NULL)/ *如果树不存在* /
flag = false;
if(p)/ * if tree退出* /
{
flag =!flag;
is_even_node(p-> left);
is_even_node(p-> right);
}
return int(flag);
}
谢谢。
@donbock
Thank you for the quick reply.
I am trying to write a function in C which returns true (1) if there are even number of nodes in a binary tree, else returns a false (0). I am attaching the code below for your refence. Please let me know if it is correct.
#include<stdio.h>
#include <stdbool.h>
bool flag = true;
int is_even_node(tree_ptr p)
{
if(p == NULL)/*if the tree does not exist*/
flag = false;
if(p)/*if the tree exits*/
{
flag = !flag;
is_even_node(p->left);
is_even_node(p->right);
}
return int (flag);
}
Thank you.
为什么不宣布你的函数返回bool?
Why don''t you declare your function to return bool?
这篇关于C中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!