Reputation: 126
Is there a way to create a new data type in C++.
I have some variables whose values are never going to be >100. So, I want to create a new datatype to store values only between 0 and 100 which would also take up less memory. I could use
unsigned short smth = 100;
but unsigned short also takes up 16 bits and there will be a lot of unused values. Something like the byte
datatype in java is needed.
16 bits probably won't matter but want to extract all the juice of performance from my application.
If it is not possible in C++ is there any way of doing it in C and implementing in C++ code?
Upvotes: 0
Views: 726
Reputation: 4827
If you want to "extract all the juice of performance from your application", you should not use other datatypes than types that are the size of a register (which may be int
in your implementation).
If you don't care about portability, I recommend using uint_fast8_t
.
It is atleast 8 bits, but the implementation uses the faster type which can be bigger
The other answers - encapsulating the functionality into a class, are also valid and should be combined with my advice.
Upvotes: 3
Reputation: 598424
For the storage, you can use (unsigned) char
, or better (u)int8_t
. Or even std::byte
in C++17 and later.
And then you can wrap that inside a class
or struct
that restricts the values that can be assigned to it.
Upvotes: 1