Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defines inside enum [duplicate]

Tags:

c

linux

enums

Inside linux kernel sources i see that, inside enums, is there also a define with the same name of enum element. Example in linux/rtnetlink.h we have:

enum {
        RTM_BASE        = 16,
#define RTM_BASE        RTM_BASE

        RTM_NEWLINK     = 16,
#define RTM_NEWLINK     RTM_NEWLINK
        RTM_DELLINK,
#define RTM_DELLINK     RTM_DELLINK
...

What is the reason for this? I can't figure out how this is used.

Thanks

like image 685
MirkoBanchi Avatar asked Oct 02 '12 10:10

MirkoBanchi


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we define enum inside a enum?

We can an enumeration inside a class. But, we cannot define an enum inside a method.

Can enum have duplicate values C++?

There is currently no way to detect or prevent multiple identical enum values in an enum.

Can we have enum containing enum with same constant?

The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc. All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.


2 Answers

One thing I could think of is that you can check for the very existence of the enum by means of the macro:

#ifdef RTM_BASE
int flag = RTMBASE;
#else
int flag = 0;
#endif

No idea if that's what's going on, though.

like image 131
Kerrek SB Avatar answered Sep 21 '22 18:09

Kerrek SB


Another thing these #defines achieve, besides allowing old code to continue the old names should the enum constant names be changed, and checking whether they are defined, is to prevent other code to define these symbols.

#include <linux/rtnetlink.h>
// for some reason, the author thinks
#define RTM_BASE 17.3f
// is a good idea

would not compile.

like image 32
Daniel Fischer Avatar answered Sep 21 '22 18:09

Daniel Fischer