Shakatir
Shakatir

Reputation: 9

Avoid macros to separate declaration from implementation

Writing some code for a data buffer I figured, it would be good to provide the maximum size of the buffer in the header through:

#define MAXIMUM_BUFFER_SIZE (SIZE_MAX - 1)

However the big disadvantage I saw in this (besides cluttering the preprocessor) was that the maximum size is actually implementation specific and might change. If other code depends on the old header but the new implementation or the other way around, it might break. Thus i thought of a more abstract way by declaring a function

size_t maximumBufferSize();

in the header and providing an implementation in the corresponding implementation file. I don't care very much about runtime, especially since the value still remains a constant, that only needs to be calculated once and can then be stored somewhere else in other code files, if necessary.

So my actual question is: Are there other pros and cons for either method, that I have to consider? And is there a third way to achieve the same result, that is maybe even better?

Upvotes: 0

Views: 55

Answers (2)

Gillespie
Gillespie

Reputation: 6561

If you are worried about SIZE_MAX changing depending on the platform or product you are using, you can always do something like this:

#ifdef RASPBERRY_PI
#define SIZE_MAX 1024
#endif

#ifdef MY_WINDOWS_PC
#define SIZE_MAX 2048
#endif

#define MAXIMUM_BUFFER_SIZE (SIZE_MAX - 1)

Upvotes: 0

L. Scott Johnson
L. Scott Johnson

Reputation: 4412

The first way is the way to go. Anything that depends on that implementation in a way that would be broken by a new implementation is poorly written and should not be considered a "con" in deciding on whether to use the best method.

The second should be used only if the size is not known at compile time.

Upvotes: 1

Related Questions