So where you put enum Status, does that replace the variable Amanda that's declared? Or would you declare it like I did, but then test it to determine if it does or doesn't?
An enum is a list of named integer values. It is a declaration, not a definition. Because it's a declaration, you can out your enums in header files.
This just declares that whn I use yes in the code, I mean 0 and when I use no I mean 1. The enum avoids hard-coded values in your programs.
So you code:
-
if (Amanda == yes)
-
cout<<"She does"<<endl;
-
else
-
cout<<"She doesn't"<<endl;
-
Rather than:
-
if (Amanda == 0)
-
cout<<"She does"<<endl;
-
else
-
cout<<"She doesn't"<<endl;
-
If you have that 0 hard-coded in 500 places and you have to change it to a 2 for some reason, you have to make 500 changes. With the enum, you just change the enum and recompile.
Enum declarations should go at the top, by function definitions or global variables, to ensure they are global in scope.
An old use for enums was enum boolean{FALSE, TRUE}, since no builtin boolean type existed in C before C99.
This makes FALSE and 0 equivalent and TRUE and 1 equivalent, so that instead of having to use 0 and 1 for, say, an isEmpty() function, you can simply use the more readable (and less likely to cause programmer error) enum.
Thus,
Code: ( text )
enum boolean {FALSE, TRUE};
SomeStructure::boolean isEmpty(){
if (size == 0)
return TRUE;
return FALSE;
}
There are some fallacies here.
One, in C, TRUE and FALSE are usually not enums but are #define macros.
Two, function defintiions and global variables do not go in header files, but enums do. Putting function definitions and global variables at the top of a source file is the old C practice used when the entire program was in one file. C++ always uses multiple files.
Three, there is no use for a global variable. I have just written an article about this that should appear in the C/C++ Articles forum shortly.
Four, you do not use TRue and FALSE in C++, and you example was a C++ example. In C++ you use the keywords
true and
false and never mind what the valus is.