A simple listing question

I just started C recently, and I was asked to answer some coding exercises in which the following code snippet appears:

typedef enum {
  false = 0,
  true = 1
} Bool;

Can someone please give a brief and clear explanation for this?

Many thanks.

+5
source share
6 answers

It really does two things; you can break something like this:

enum _bool {
   false = 0,
   true = 1
};

AND:

typedef enum _bool Bool;

This code creates a new enumeration type and then uses typedefit to give it a convenient name. This will allow you to use the new “type” called Boolelsewhere in your code and assign values ​​to it falseand true. Here is a simple usage example:

Bool logical_not(Bool in)
{
    if (in == true)
        return false;
    else
        return true;
}
+11
source

, , , .. , . , . , , , .

. wiki (, , C ) .

, , : true false, false =! true. , , , , , (, ++ C99).

, , :

enum Bool
{
    false = 0,
    true = 1
};

; - , C Bool , enum Bool:

enum Bool myFlag=true;

typedef, , , Bool; :

Bool myFlag=true;
+4

C , , typedef.

:

Bool find_key_in_array() {
        Bool found = false; // assume not found.

        // do searching and set found suitably.    

        return found;
}

int main()  {

        Bool result = find_key_in_array();

        return 0;
}
+1

. , .

? ( enum) , typedef ... Bool; Bool - .

,

int flag=false;
// something happens that might change the setting of flag that *doesn't* use the enum
if (flag == true) {
   //...
}

flag 2, , .

c, , , .

+1

, . , :

Bool finish = false;

while (finish != true)
{
    ...
}
+1

, :

This declares the enumeration, and then associates the name Bool with this enumeration (via typedef ). You can get more information about C listings here.

0
source

All Articles