简体   繁体   中英

C++ Single value enums versus preprocessor directives

Very simple question about best practices and performance. I know that it's a bad idea to use bare constants in your code directly (eg -1 meaning "unassigned"). I generally don't like using the preprocessor for such things if I can help it, since I don't like shouting (eg #define UNASSIGNED -1 ) and don't like breaking with the convention of putting preprocessor names in all caps. So I've taken to using anonymous enums:

enum {
  Unassigned = -1
};

Question: Is there any runtime performance penalty for this compared to the preprocessor approach? Is this a bad idea?

There is no runtime performance impact - the compiler will know they're just the value -1 in both cases.

However, I believe the best approach is to use a correctly typed constant for this. For example:

const int Unassigned = -1;

(Substitute your actual type for int , of course).

There should be no performance impact. However, why not just const int Unassigned = -1 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM