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.
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:
typedef
Bool
false
true
Bool logical_not(Bool in) { if (in == true) return false; else return true; }
, , , .. , . , . , , , .
. 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;
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; }
. , .
? ( enum) , typedef ... Bool; Bool - .
enum
typedef ... Bool;
,
int flag=false; // something happens that might change the setting of flag that *doesn't* use the enum if (flag == true) { //... }
flag 2, , .
flag
c, , , .
, . , :
Bool finish = false; while (finish != true) { ... }
, :
This declares the enumeration, and then associates the name Bool with this enumeration (via typedef ). You can get more information about C listings here.