Hello, welcome back to the C++ learning tutorial series.
This time we will discuss the Enum data type.
What is an Enum?
Why do we need Enum?
How do you create an enum and use it in a C++ program?
Let's discuss…
What is an Enum?
Enum or Enumeration is a data type that contains a set of constants .
So, with Enum.. we can store multiple constants in one variable.
Here's how to create an enum:
Here's how to create an enum:
Example:
enum level {EASY = 1, NORMAL = 2, HARD = 3};
enum sex {MALE, FEMALE};
enum state {PENDING, INPROGRESS, DONE};
When we don't fill the constant value in the enum…
...then by default it will be filled with numbers that follow the order in which they were written.
Example:
enum hari {SENIN, SELASA, RABU, KAMIS, JUMAT, SABTU, MINGGU};
Then the constants in the enum hari
will have the value:
SENIN = 0
SELASA = 1
RABU = 2
KAMIS = 3
JUMAT = 4
SABTU = 5
MINGGU = 6
So it's similar to an array, but the difference is that what is stored in an enum is not a variable... but a constant whose value we cannot change.
Why do we need Enums?
Enums make it easy for us to store several constants that are still in one group into one variable. So it will make the code easy to understand.
For example, if we want to save the order status... we can create constants one by one like this.
const int PENDING = 1;
const int CANCELED = -1;
const int PAID = 2;
const int SHIPPING = 3;
const int DELIVERED = 4;
But if later we use a lot of constants with the same name, then we will be confused about reading them.
Therefore, constants that are still in the same group... it's best to put them in one place so that it's easy.
So we can create an enum like this:
enum OrderStatus = { PENDING, CANCELLED = -1, PAID, SHIPPING, DELIVERED };
Then, we can use it like this:
OrderStatus status = PENDING;
Now let's try practice.
Creating Programs with Enums
Now let's try to create a program with enums.
Please create a new program called contoh_enum.cpp
, then fill it with the following code.
#include <iostream>
using namespace std;
enum Role { USER, ADMIN };
int main() {
string name = "Petani Kode";
Role user_role = USER;
if(user_role == ADMIN) {
cout << "Welcome Admin" << endl;
} else {
cout << "Hello, " << name << endl;
}
return 0;
}
After that, try compiling and running...
So the result is:
Now try changing it user_role
with ADMIN
, so it looks like this:
#include <iostream>
using namespace std;
enum Role { USER, ADMIN };
int main() {
string name = "Petani Kode";
Role user_role = ADMIN;
if(user_role == ADMIN) {
cout << "Welcome Admin" << endl;
} else {
cout << "Hello, " << name << endl;
}
return 0;
}
Then compile and run again.
then the result:
In this example case, we use an enum to store constants that represent the role of the user.
Still confused?
That's okay, in the future, if you use enums often, you'll understand.
Using Enums As Flags
Flags means flags, in programming... These flags can be interpreted as markers.
Case example:
For example, if we want to create an access rights program, we can create flags: READ
, WRITE
, DELETE
.
Later, the data that we give the flag will be able to access according to the flag that we give.
Let's try to make it in practice!
Create a new file with the name enum_flag.cpp
then fill it with the following code:
#include <iostream>
using namespace std;
int main() {
enum Permission { READ = 1, WRITE = 2, DELETE = 4};
int balance = 0;
// set flags dengan operasi bitwise or
Permission userPermission = Permission(READ | WRITE);
if(userPermission & WRITE){
cout << "Anda dibolehkan mengisi saldo\n";
balance += 100;
}
cout << "Saldo:" << balance << endl;
return 0;
}
After that, try compiling and running it.
So the result is:
Take note!
In this example case we fill in the flag values READ=1
, WRITE=2
, and DELETE=4
.
Why is it filled like that?
This is so that if it is converted to binary with the bitwise OR ( |
) operation, the binary does not conflict. Remember, bitwise operations are operations carried out based on binary.
For example:
READ | WRITE
If in binary:
READ = 0001;
WRITE = 0010;
// maka
READ | WRITE = 0011;
OK, now try changing it userPermission
.
We remove the flag WRITE
, so now the binary will be 0001
.
So the code becomes like this:
#include <iostream>
using namespace std;
int main() {
enum Permission { READ = 1, WRITE = 2, DELETE = 4};
int balance = 0;
// set flags dengan operasi bitwise or
Permission userPermission = Permission(READ);
if(userPermission & WRITE){
cout << "Anda dibolehkan mengisi saldo\n";
balance += 100;
}
cout << "Saldo:" << balance << endl;
return 0;
}
Then try compiling and running again.
So the result is:
The balance doesn't change, this is because we didn't give WRITE
the variable a flag userPermission
.
So that during operation userPermission & WRITE
it will produce false.
Scoped Enum di C++
Take a look at the examples of exercises we have just created.
In the example, we create an enum outside the function main()
and also inside the function main()
.
It's called: Unscoped Enum
What is an Unscoped Enum ?
Unscped enum is an enum that is globally scoped. This means that we can directly access what is in the enum .
For example:
enum Task { PENDING, PROGRESS, DONE };
So, Task
we can access the enum directly like this:
Task newTask = PENDING;
It's different with Scoped Enum .
Scoped Enum * is an enum whose contents can be accessed within a certain scope.
As an example:
We create an enum in a Struct.. then the enum will only be accessible through that Struct.
Pay attention to this code:
struct Player {
int health;
enum Role {P1, P2};
}
In this code there is a struct Player
and in it there is an enum Role
containing P1
and P2
.
If we want to access enum Role
, we have to go through the struct Player
first.
The method is like this:
Player::Role p1 = Player::Role::P1;
Tags ::
are operators for accessing members of Structs, Classes, and Namespaces.
In this example, we access the enum P1
by Player::Role::P1
. Oh yes, this can be done in the C++11
old version, but in the old version it won't work. 1
OK, let me understand better...
..let's try the scoped enum exercise .
Create a new file with the name enum_scoped.cpp
, then fill it with the following code:
#include <iostream>
using namespace std;
// membuat scoped enum di dalam struct
struct Car {
int speed;
enum EngineStatus { ON, OFF };
enum Direction { FORWARD, BACKWARD };
Direction direction;
EngineStatus engineState;
};
// membuat scoped enum di dalam class
enum class LampColor { RED, YELLOW, GREEN };
int main(){
Car honda = {
.speed = 40,
.engineState = Car::EngineStatus::ON
};
LampColor lampColor = LampColor::GREEN;
if(lampColor == LampColor::GREEN){
honda.direction = Car::Direction::FORWARD;
}
cout << "Kecepatan mobil: " << honda.speed << endl;
cout << "Engine: " << honda.engineState << endl;
cout << "Direction: " << honda.direction << endl;
return 0;
}
After that, compile and run.
So the result is:
In this example, we create two scoped enums. That is, enum in the struct Car
and enum in the class LampColor
.
There are two enums in Struct Car
, namely EngineStatus
and Direction
.
Then, when accessing the value in the scoped enum... we have to go through the Struct Car
and also the class LampColor
.
What is next?
So far, we've learned about enums and practiced using them.
What you need to understand and remember is:
The enum contains a collection of constants whose contents are numbers (integers).
Next, please learn about Structs in C++.
Happy learning! 🙌
Post a Comment