program tip

C에서 부울 값 사용

radiobox 2020. 10. 2. 21:58
반응형

C에서 부울 값 사용


C에는 내장 부울 유형이 없습니다. C에서 사용하는 가장 좋은 방법은 무엇입니까?


좋은 것에서 나쁜 것까지 :

옵션 1 (C99)

#include <stdbool.h>

옵션 2

typedef enum { false, true } bool;

옵션 3

typedef int bool;
enum { false, true };

옵션 4

typedef int bool;
#define true 1
#define false 0

설명

  • 옵션 1은 C99를 사용하는 경우에만 작동하며이를 수행하는 "표준 방법"입니다. 가능하면 이것을 선택하십시오.
  • 옵션 2, 3 및 4는 실제로 동일한 동작을 갖습니다. # 2와 # 3은 #defines를 사용하지 않습니다.

미정이라면 # 1!


C의 부울에 대한 몇 가지 생각 :

나는 int참 / 거짓 값에 대한 typedef 또는 특수 정의 또는 열거 형없이 일반 s를 부울 유형으로 사용하기에 충분히 늙었습니다 . 부울 상수와 비교하지 않는 것에 대한 아래의 제안을 따르면 어쨌든 0/1을 사용하여 플래그를 초기화하면됩니다. 그러나 이러한 접근 방식은 현대에 너무 반동적 인 것으로 간주 될 수 있습니다. 이 경우 <stdbool.h>최소한 표준화의 이점이 있기 때문에 반드시 사용해야 합니다.

어떤 부울 상수가 호출 되든 초기화에만 사용하십시오. 다음과 같이 쓰지 마십시오.

if (ready == TRUE) ...
while (empty == FALSE) ...

이들은 항상 더 명확한 것으로 대체 될 수 있습니다

if (ready) ...
while (!empty) ...

이것들은 실제로 합리적이고 이해하기 쉽게 큰 소리로 읽을 수 있습니다.

당신의 부울 변수를 긍정적 인 이름, 즉주고 full대신을 notfull. 후자는 읽기 어려운 코드로 이어집니다. 비교

if (full) ...
if (!full) ...

if (!notfull) ...
if (notfull) ...

이전 쌍은 모두 자연스럽게 읽지 만있는 그대로 !notfull도 읽기가 어색하며 더 복잡한 부울 표현에서는 훨씬 더 나빠집니다.

부울 인수는 일반적으로 피해야합니다. 다음과 같이 정의 된 함수를 고려하십시오.

void foo(bool option) { ... }

함수 본문 내에서 인수의 의미는 편리하고 의미있는 이름을 가지고 있기 때문에 매우 명확합니다. 그러나 통화 사이트는 다음과 같습니다.

foo(TRUE);
foo(FALSE):

여기서는 항상 함수 정의 나 선언을 보지 않고는 매개 변수가 의미하는 바를 말할 수 없으며, 더 많은 부울 매개 변수를 추가하면 훨씬 더 나빠집니다. 나는 둘 중 하나를 제안한다

typedef enum { OPT_ON, OPT_OFF } foo_option;
void foo(foo_option option);

또는

#define OPT_ON true
#define OPT_OFF false
void foo(bool option) { ... }

두 경우 모두 통화 사이트는 다음과 같습니다.

foo(OPT_ON);
foo(OPT_OFF);

which the reader has at least a chance of understanding without dredging up the definition of foo.


A boolean in C is an integer: zero for false and non-zero for true.

See also Boolean data type, section C, C++, Objective-C, AWK.


Here is the version that I used:

typedef enum { false = 0, true = !false } bool;

Because false only has one value, but a logical true could have many values, but technique sets true to be what the compiler will use for the opposite of false.

This takes care of the problem of someone coding something that would come down to this:

if (true == !false)

I think we would all agree that that is not a good practice, but for the one time cost of doing "true = !false" we eliminate that problem.

[EDIT] In the end I used:

typedef enum { myfalse = 0, mytrue = !myfalse } mybool;

to avoid name collision with other schemes that were defining true and false. But the concept remains the same.

[EDIT] To show conversion of integer to boolean:

mybool somebool;
int someint = 5;
somebool = !!someint;

The first (right most) ! converts the non-zero integer to a 0, then the second (left most) ! converts the 0 to a myfalse value. I will leave it as an exercise for the reader to convert a zero integer.

[EDIT] It is my style to use the explicit setting of a value in an enum when the specific value is required even if the default value would be the same. Example: Because false needs to be zero I use false = 0, rather than false,


If you are using a C99 compiler it has built-in support for bool types:

#include <stdbool.h>
int main()
{
  bool b = false;
  b = true;
}

http://en.wikipedia.org/wiki/Boolean_data_type


First things first. C, i.e. ISO/IEC 9899 has had a boolean type for 19 years now. That is way longer time than the expected length of the C programming career with amateur/academic/professional parts combined when visiting this question. Mine does surpass that by mere perhaps 1-2 years. It means that during the time that an average reader has learnt anything at all about C, C actually has had the boolean data type.

For the datatype, #include <stdbool.h>, and use true, false and bool. Or do not include it, and use _Bool, 1 and 0 instead.


There are various dangerous advice in this answer thread. I will address them:

typedef int bool;
#define true 1
#define false 0

This is no-no, because a casual reader - who did learn C within those 19 years - would expect that bool refers to the actual bool data type and would behave similarly, but it doesn't! For example

double a = ...;
bool b = a;

With C99 bool/ _Bool, b would be set to false iff a was zero, and true otherwise. With the typedef in place, the double would be coerced to an int - if the value of the double isn't in the range for int, the behaviour is undefined.

Naturally the same applies to if true and false were declared in an enum.

What is even more dangerous is declaring

typedef enum bool {
    false, true
} bool;

because now all values besides 1 and 0 are invalid, and should such a value be assigned to a variable of that type, the behaviour would be wholly undefined.

Therefore iff you cannot use C99 for some inexplicable reason, for boolean variables you should use:

  • type int and values 0 and 1 as-is; and carefully do domain conversions from any other values to these with double negation !!
  • or if you insist you don't remember that 0 is falsy and non-zero truish, at least use upper case so that they don't get confused with the C99 concepts: BOOL, TRUE and FALSE!

typedef enum {
    false = 0,
    true
} t_bool;

C has a boolean type: bool (at least for the last 10(!) years)

Include stdbool.h and true/false will work as expected.


Anything nonzero is evaluated to true in boolean operations, so you could just

#define TRUE 1
#define FALSE 0

and use the constants.


Just a complement to other answers and some clarification, if you are allowed to use C99.

+-------+----------------+-------------------------+--------------------+
|  Name | Characteristic | Dependence in stdbool.h |        Value       |
+-------+----------------+-------------------------+--------------------+
| _Bool |   Native type  |    Don't need header    |                    |
+-------+----------------+-------------------------+--------------------+
|  bool |      Macro     |           Yes           | Translate to _Bool |
+-------+----------------+-------------------------+--------------------+
|  true |      Macro     |           Yes           |   Translate to 1   |
+-------+----------------+-------------------------+--------------------+
| false |      Macro     |           Yes           |   Translate to 0   |
+-------+----------------+-------------------------+--------------------+

Some of my preferences:

  • _Bool or bool? Both are fine, but bool looks better than the keyword _Bool.
  • Accepted values for bool and _Bool are: false or true. Assigning 0 or 1 instead of false or true is valid, but is harder to read and understand the logic flow.

Some info from the standard:

  • _Bool is NOT unsigned int, but is part of the group unsigned integer types. It is large enough to hold the values 0 or 1.
  • DO NOT, but yes, you are able to redefine bool true and false but sure is not a good idea. This ability is considered obsolescent and will be removed in future.
  • Assigning an scalar type (arithmetic types and pointer types) to _Bool or bool, if the scalar value is equal to 0 or compares to 0 it will be 0, otherwise the result is 1: _Bool x = 9; 9 is converted to 1 when assigned to x.
  • _Bool is 1 byte (8 bits), usually the programmer is tempted to try to use the other bits, but is not recommended, because the only guaranteed that is given is that only one bit is use to store data, not like type char that have 8 bits available.

@Thomas Matthews: Conditional expressions are considered to be true if they are non-zero, but the C standard requires that logical operators themselves return either 0 or 1.

@Tom: #define TRUE !FALSE is bad and is completely pointless. If the header file makes its way into compiled C++ code, then it can lead to problems:

void foo(bool flag);

...

int flag = TRUE;
foo(flag);

Some compilers will generate a warning about the int => bool conversion. Sometimes people avoid this by doing:

foo(flag == TRUE);

to force the expression to be a C++ bool. But if you #define TRUE !FALSE, you end up with:

foo(flag == !0);

which ends up doing an int-to-bool comparison that can trigger the warning anyway.


It is this:

#define TRUE 1
#define FALSE 0

You can use a char, or another small number container for it.

Pseudo-code

#define TRUE  1
#define FALSE 0

char bValue = TRUE;

You could use _Bool, but the return value must be an integer (1 for true, 0 for false). However, It's recommended to include and use bool as in C++, as said in this reply from daniweb forum, as well as this answer, from this other stackoverflow question:

_Bool: C99's boolean type. Using _Bool directly is only recommended if you're maintaining legacy code that already defines macros for bool, true, or false. Otherwise, those macros are standardized in the header. Include that header and you can use bool just like you would in C++.


If your using c99 you can use the _Book type which is part of c99 I.e no #includes' are necessary. You do need to treat it like an int though, where 1 = true and 0 = false. You can then define TRUE and FALSE.

_Bool this_is_a_Boolean_var = 1;


//or using it with true and false
#define TRUE 1
#define FALSE 0
_Book var = TRUE;

You can simply use #define directive as follows:

#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;

And use as follows:

bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);

and so..on

참고URL : https://stackoverflow.com/questions/1921539/using-boolean-values-in-c

반응형