Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I use #define, enum or const?
    text
    copied!<p>In a C++ project I'm working on, I have a <em>flag</em> kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:</p> <ul> <li>new record</li> <li>deleted record</li> <li>modified record</li> <li>existing record</li> </ul> <p>Now, for each record I wish to keep this attribute, so I could use an enum:</p> <pre><code>enum { xNew, xDeleted, xModified, xExisting } </code></pre> <p>However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: </p> <pre><code>showRecords(xNew | xDeleted); </code></pre> <p>So, it seems I have three possible appoaches:</p> <pre><code>#define X_NEW 0x01 #define X_DELETED 0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08 </code></pre> <p>or</p> <pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; </code></pre> <p>or </p> <pre><code>namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8; } </code></pre> <p>Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with <code>enum</code> I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With <code>const</code> I think I also lose type safety since a random <code>uint8</code> could get in by mistake.</p> <p>Is there some other cleaner way?</p> <p>If not, what would you use and why?</p> <p>P.S. The rest of the code is rather clean modern C++ without <code>#define</code>s, and I have used namespaces and templates in few spaces, so those aren't out of question either.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload