I need to store exactly four boolean elements in my structure in c. Yes, I could use four integers or put them in an array, but I would like to make it a little better. I thought of int as "0000", where each number will be a boolean, but then when editing, I canβt edit just one digit, right? It doesn't look perfect ...
Thanks for any ideas.
You can use the structure of the bit field:
struct foo { unsigned boolean1 : 1; unsigned boolean2 : 1; unsigned boolean3 : 1; unsigned boolean4 : 1; };
Then you can easily edit each boolean separately, for example:
struct foo example; example.boolean1 = 1; example.boolean2 = 0;
Using an int of type β0000β is called using a bit field and is performed fairly regularly in practice. Yes, you can edit single values ββusing bit offsets . Personally, I would prefer to use int for the structure of the bit field, since you can expand up to 32 values ββ(if you use a 32-bit int, of course) without changing the structure.
If you store millions, do it like packed bits.
If you need to access it millions of times per second, do it as ints (or shorts or characters).
If not, it does not matter.
If both of them, then you can have a serious performance tuning.
Can be done using
http://en.wikipedia.org/wiki/Stdbool.h
bool a = true; // Could also be 'bool a = 1;'
struct _eMyBool { int m_iOne : 1; int m_iTwo : 1; int m_iThree : 1; int m_iFour : 1; } eMyBool;
However, do not even think that this is the most efficient way to use logical ones.
Because the extra build code generated to handle this has a price!
For example, read this MSDN article.
AFAI remember, I think that there should be a ratio of at least 7 for the acquired memory, because the trace of the additional code for bit movement when accessing the one-bit alignment element is really significant.
This is a wikipedia article on data alignment.
Source: https://habr.com/ru/post/1334004/More articles:Creating a nested model - ruby ββ| fooobar.comThe task of the function of the C ++ template - c ++Linking two models in multi-model form - ruby ββ| fooobar.comNo letters of confirmation have been received. How to configure it? - ruby-on-railsconversion from int to hex - stringcss absolute positioning of hidden scrollbars ... with swirl - cssHow can I define a character or string constant in C # for ASCII 127? - stringwill work with HTML5? - html5AJAX - how to determine the best polling rate? - javascriptHow to create a Facebook application in Google App Engine? - google-app-engineAll Articles