xxxxxxxxxx
enum Color { red, green, blue };
Color r = red;
switch(r)
{
case red : std::cout << "red\n"; break;
case green: std::cout << "green\n"; break;
case blue : std::cout << "blue\n"; break;
}
Safer than simple enum
xxxxxxxxxx
// Declaration
enum class Color{ Red, Green, Blue};
// Initialisation
Color col = Color::Red;
xxxxxxxxxx
#include <iostream>
using namespace std;
// Creating an enum type
enum Weather {
Rainy, // Starts from 0
Cool, // This is 1
Thunderstorm, // This is 2
VeryBright // This is 3
// And continues...
};
/* Your Programs starts here */
int main()
{
// Creates a enum variable & assigning it into Rainy
Weather currentWeather = Rainy;
// Outputs 0 because its the first one
cout << currentWeather << endl;
// Changes the variable into VeryBright
currentWeather = VeryBright;
// Outputs 3 because its the last one
cout << currentWeather << endl;
return 0;
}
/* Output C:\EnumsExample.exe :
0
3
\\\end\\\
*/
xxxxxxxxxx
enum Animal{
dog, // Same as dog = 0
cat, // Same as cat = 1
parrot, // Same as parrot = 2
};
enum Car{
Ford = 3,
Nissan = 4,
Honda = 21,
};
//In main
std::cout << dog << std::endl; // Prints 0
std::cout << Ford << std::endl; // Prints 3
Car myCar = Nissan;
std::cout << myCar << std::endl; // Prints 4
if(myCar == Ford){ // False
//...
}else if(myCar == Nissan){ // True
//...
}
xxxxxxxxxx
enum Foo { a, b, c = 10, d, e = 1, f, g = f + c };
//a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12
xxxxxxxxxx
#include <iostream>
using namespace std;
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday = 6};
//by deafult Sunday will be 0, Monday 1 etc...
//you can change the value like we did on saturday
int main()
{
week today;//you can use the enum as a type or you can use int (enum stores int values)
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
xxxxxxxxxx
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Defining enum Gender
enum Gender { Male, Female };
// Creating Gender type variable
Gender gender = Male;
switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
xxxxxxxxxx
enum Color { red, green, blue };
Color r = red;
switch(r)
{
case red : std::cout << "red\n"; break;
case green: std::cout << "green\n"; break;
case blue : std::cout << "blue\n"; break;
}
xxxxxxxxxx
/* Defining the enum */
enum vals {val1, val2, val3};
/* Setting a variable to an enum's value */
vals some_val;
some_val = val3;