Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit cpp enum #5548

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion content/cpp/concepts/enum/enum.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
Title: 'Enums'
Description: 'In C++, an enumeration (enum) is a user defined type where a set of values are specified for a variable and the variable can only take one out of a small set of possible values.'
Description: 'In C++, an enum defines a variable with a limited set of predefined values.'
Subjects:
- 'Computer Science'
- 'Game Development'
Expand Down Expand Up @@ -102,3 +102,45 @@ LogResult logger_result = LogResult::Success;

if (logger_result == LogResult::Success) {} // Because Success is scoped to LogResult, it doesn't collide with SocketResult::Success
```

## Enum to Int Conversion

In C++, enums can be implicitly converted to integers, useful for numeric contexts like array indexing or bitwise operations.

```cpp
enum color { red, green, blue };

int main() {
color c = green;
int colorValue = c; // Implicit conversion to int
std::cout << "Color value: " << colorValue; // Output: Color value: 1
}
```

Converting an enum to int is easy, but converting int to enum is risky as no bounds check is done, leading to undefined behavior if the value is out of range.

## Custom Underlying Type for Enums

By default, an enum's type is int, but you can specify a smaller type like unsigned char to optimize memory usage.

```cpp
enum class Permission : unsigned char {
Read = 1,
Write = 2,
Execute = 4
};

int main() {
Permission p = Permission::Write;
std::cout << static_cast<int>(p); // Explicit cast to int: Output: 2
}
```

Here, the underlying type of Permission is unsigned char. The constants Read, Write, and Execute are stored using only 1 byte of memory.

## Best Practices for Using Enums

1. Use enum class for Strong Typing: Scoped enums (C++11) prevent implicit int conversions, ensuring better type safety.
2. Explicit Casting: Use static_cast<int>(enum_value) for safe conversions.
3. Avoid Magic Numbers: Enums replace hardcoded numbers, improving readability.
4. Use Underlying Types Wisely: Choose the underlying type carefully in memory-constrained environments.
Loading