Reputation: 2100
How can I structure some C code so that I don't have to laboriously go back and
redefine (i.e., #define
) things when I need to add a new item in the middle.
Here is a code sample (in the real code, there are about 200 different
defines):
#define CREAM 1
#define SALT 2
#define BUTTER 3
#define SUGAR 4
#define FAT 5
void healthyDiet()
{
int length = 10;
int menu[500];
void consume(int, int);
// ****** these must be called in the following order only
consume( menu[ CREAM ], length);
consume( menu[ SALT ], length);
consume( menu[ BUTTER ], length);
consume( menu[ SUGAR ], length);
consume( menu[ FAT ], length);
}
But now I need to #define
and add LARD
, which would be straightforward if the sequence
here were not important. But LARD
must come before SUGAR
and after BUTTER
. So
I now need to edit the defines:
#define CREAM 1
#define SALT 2
#define BUTTER 3
#define LARD 4
#define SUGAR 5 // changed from 4
#define FAT 6 // changed from 5
So how can I structure things so that each time I want to add something in the middle, I don't have to go back and manually change the define value for each item?
Upvotes: 2
Views: 272
Reputation: 9821
Check out enumerations: http://crasseux.com/books/ctutorial/enum.html
enum {CREAM, SALT, BUTTER, LARD, BACON, SUGAR};
Upvotes: 3
Reputation: 11162
You're looking for enum
enum {CREAM, SALT, BUTTER, LARD, SUGAR};
To add anoter element, just add it:
enum {CREAM, SALT, BUTTER, LARD, BACON, SUGAR};
You can even use this like a psudeo-iterator:
enum {FIRST_ONE, CREAM=0, SALT, BUTTER, LARD, BACON, SUGAR, LAST_ONE};
void healthyDiet()
{
int length = 10;
int menu[500];
void consume(int, int);
int x;
for(x=FIRST_ONE; x<LAST_ONE; x++)
consume( menu[ x ], length);
}
Upvotes: 5