patterncppMinor
Implementing Tribool with int8_t
Viewed 0 times
withtriboolimplementingint8_t
Problem
For digital electronic circuit simulation, i wanted to implement Three states. i.e High, Low and Undefined in C++.
I saw
Now for conserving some memory i have implemented it using 1 Byte Int
I saw
Boost::tribool, and they implement it using enumNow for conserving some memory i have implemented it using 1 Byte Int
#ifdef _WINDOWS
typedef __int8 State;
#elif
typedef int8_t State;
#endif
const State kLow = 0;
const State kHigh = 1;
const State kUndefined = 2;- Do you see any potential problem with it?
- And why would one waste 4 bytes instead of a single byte for 3 values only
- Do you have a still better way?
Solution
The main reason there is no accidental conversion (type safety is one of the keys to using C++ correctly).
Secondly you are using three bytes to hold the different states here
With an enum there is no space taken up (though potentially the above may be optimized out).
C++11 also allows you to specify the size of an enum:
Do you see any potential problem with it?
Yes. Not type safe
And why would one waste 4 bytes instead of a single byte for 3 values only
Why not. Does it really matter in any modern PC.
OK for embedded systems maybe (but you obviously are using WINDOWS)
Do you have a still better way?
Yes. Use enum in C++11
enum Tri { Yes, No, Maybe };
int main()
{
Tri y = Yes;
y= 1; // Fails to compile.
}Secondly you are using three bytes to hold the different states here
const State kLow = 0;
const State kHigh = 1;
const State kUndefined = 2;With an enum there is no space taken up (though potentially the above may be optimized out).
C++11 also allows you to specify the size of an enum:
enum class Tri : char { Yes, No, Maybe };
// ^^^^ Uses a char sized objectDo you see any potential problem with it?
Yes. Not type safe
And why would one waste 4 bytes instead of a single byte for 3 values only
Why not. Does it really matter in any modern PC.
OK for embedded systems maybe (but you obviously are using WINDOWS)
Do you have a still better way?
Yes. Use enum in C++11
Code Snippets
enum Tri { Yes, No, Maybe };
int main()
{
Tri y = Yes;
y= 1; // Fails to compile.
}const State kLow = 0;
const State kHigh = 1;
const State kUndefined = 2;enum class Tri : char { Yes, No, Maybe };
// ^^^^ Uses a char sized objectContext
StackExchange Code Review Q#7262, answer score: 5
Revisions (0)
No revisions yet.