Reputation:
I want to add a new file format into my project. So I am #define
ing a new file format type, but I want to keep support for the old format too.
Does my setup/structure of #ifdef
s and #else
s make sense, is it valid? I'm pretty sure it is, but I feel without braces it doesn't make sense.
// My intention
if()
;
else
{
if()
;
else
;
}
.
#ifdef FILE_FORMAT_TWO
sprintf(xxx);
#else
#ifdef NEW_FILE_FORMAT
sprintf(xxx);
#else
sprintf(xxx);
#endif
sprintf(xxx);
#endif
Is there a prettier way to do this?
EDIT: What I mean to say, is the first section of code is what I mean to do with the #
(pound defines, ifs, and elses) in the second section. I was not sure if the second section read the same as the first. I wrote the second section as such because I didn't realize to use #elif
, I was missing that piece of information.
Upvotes: 1
Views: 1587
Reputation: 1723
#ifdef FILE_FORMAT_TWO
sprintf(xxx);
#elif defined(NEW_FILE_FORMAT)
sprintf(xxx);
#else
sprintf(xxx);
#endif
And here is an explanation. The C pre-processor directives permit you to use #ifdef
as a shortform for #if defined
. The Gnu C compiler's pre-processor directives can be found here. That document is somewhat long, so the portion that pertains to conditional syntax lies here.
In general though, I've found it cleaner to be explicit in my pre-processing directives, like so:
#if defined(FILE_FORMAT_TWO)
sprintf(xxx);
#elif defined(NEW_FILE_FORMAT)
sprintf(xxx);
#elif defined(DEFAULT_FILE_FORMAT)
sprintf(xxx);
#else
#error "You must define blah blah"
#endif
Credits to Jonathan Leffler for pointing out the stylistic inconsistency in #ifdef FILE_FORMAT_TWO
and suggesting replacement with #if defined (FILE_FORMAT_TWO)
Upvotes: 0
Reputation: 1582
#ifdef FILE_FORMAT_TWO
sprintf(xxx);
#else
#ifdef NEW_FILE_FORMAT
sprintf(xxx);
#else
sprintf(xxx);
#endif
sprintf(xxx); <<---- remove this
#endif
But I think that it would be better something like:
#define FILE_FORMAT 1
and
#if FILEFORMAT == 1
#elif FILEFORMAT == 2
#else
#endif
Upvotes: 3