1

Very simple question about best practices and performance. I know that it's a bad idea to use bare constants in your code directly (e.g. -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 (e.g. #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?

2
  • 3
    Have you considered static const variables? I'm not suggesting it, just questioning. Commented Jan 15, 2014 at 15:05
  • 1
    likewise, have you considered if in case you need multiple such constants, that somehow belong together, an enum class is a possible solution? Commented Jan 15, 2014 at 15:09

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed. Now that you mention it, in C++11 it's probably even better to use constexpr int Unassigned = -1;
3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.