简体   繁体   中英

Is it a good practice to group related constants using structs in C?

I was wondering if it would be a good idea to use structs as pseudo namespaces (à la C++) to group constants which are functionally or conceptually related to each other.

static const struct {

    const unsigned int START;
    const unsigned int END;

} COUNTER = {.START = 1, .END = 100};

Is there any downside to this? If not, is it redundant (or maybe even unconvenient) to have both the struct instance and its members declared as const ? Where should the constantness of these values be stated?

I was wondering if it would be a good idea to use structs as pseudo namespaces

Well, it CAN be a good idea. It's not intrinsically bad. An argument against is that if you feel that you need namespaces, then it's likely that C is the wrong language in the first place. But it can be used this way, and it is sometimes used this way.

Where should the constantness of these values be stated?

It's in general enough to declare the whole struct as const. But beware with pointers. This code is valid and will print "42":

int x = 5;

const struct {
        int *p;
} S = {.p = &x };

int main()
{
        *(S.p) = 42;
        printf("%d\n", x);
}

In the above code, you are not allowed to change Sp so that it points to something else, but there is a difference between a const pointer and a pointer to const. So for pointer, it could be a good idea to add an extra const.

To clarify, the pointer p will be declared like it was a int * const p which means you cannot change the pointer itself, but in order to protect the data it's pointing to, you need const int *p . To get both, use const int * const p , but if the struct is declared as const, you'll get one of them "for free" so const int *p is enough to get both.

And if you consider pointers to pointers, well, think it through for a long time and test it to make sure it works the way you want.

From comments:

Why not enums?

Because this is not valid:

enum S {a = 5};
enum Y {a = 6};

The compiler will tell you that a is already defined. So enums is not good for emulating namespaces. Also, you cannot use enums for non-integers.

Is it a good practice to group related constants using structs in C?

It's opinion based. If it works for you, do it.

I wouldn't do like that i C. Instead I use #define

Like:

#define GROUPNAME_NAME

so in your case I would do

#define COUNTER_START 1
#define COUNTER_END 100

In C++ I would do:

const unsigned int COUNTER_START = 1;
const unsigned int COUNTER_END = 100;

The difference between C and C++ is due to differences in language specification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM