Reputation: 175
I have a requirement that states a function should take in one new argument at the beginning of the argument list for a new platform I am working on.
so the following would be a prototype for this new platform
void foo (int newarg, const char * a, int b, int c);
where as in the previous case it was just
void foo (const char * a, int b, int c);
My concern is readability and code space . So I am thinking of using ifdefs but i am not sure if it is a good idea to use if def with in a argument list.
1)
void foo (
#ifdef __NEWPLATFORM__
int newarg,
#else
const char * a, int b, int c
#endif
);
or
#if __NEWPALTFORM__
void foo (int newarg, const char * a, int b, int c);
#else
void foo (const char * a, int b, int c);
#endif
Btw I cannot put the new argument to the end of the list which would make it a lot easier.
Which one of the two (or maybe a better solution) is better?
Thanks
Upvotes: 1
Views: 2137
Reputation: 921
A third option would be to conditionally define a symbol for the extra argument. You might use the #ifdef section to include other useful platform related stuff, for example:
#ifdef MY_NEW_PLATFORM
#define EXTRA_ARGS int newarg,
#define GET_EXTRA newarg
#define SET_EXTRA(val) newarg = (val)
#else
#define EXTRA_ARGS
#define GET_EXTRA 0
#define SET_EXTRA(val)
#endif
...
void foo (EXTRA_ARGS const char * a, int b, int c) {
b = GET_EXTRA + c; /* Just as example */
SET_EXTRA(b+c);
}
As you can see, the foo function has no distracting "#ifdefs", and it compiles in any platform.
Upvotes: 1
Reputation: 44306
Given that you are changing all the calls to foo
,
just change foo
to the function with more parameters, then #ifdef
internal to the function for different functionality.
void foo (int newarg, const char * a, int b, int c){
#ifdef __NEWPALTFORM__
#else
#endif
}
Also worth considering whether the parameters to the function should really be a struct, in which case new parameters in the future won't be much of an issue. Not enough context in your question to say whether this is a good idea or not
but it would be something like :=
typedef struct {
int newarg;
const char* a;
int b;
int c;
} fooType;
void foo(fooType f) // either by value or by pointer depending on context
{
// #ifdefs...
}
Upvotes: 2