[riot-devel] enums vs. macros

Kaspar Schleiser kaspar at schleiser.de
Wed May 13 10:15:11 CEST 2015


Hey,

On 05/13/15 08:12, Oleg Hahm wrote:
>> Because flags have a width in memory that is in most cases smaller than
>> sizeof(enum) (most bit fields I know of are 16 bits max, on most of our
>> newer platforms, sizeof(enum) is however 32 bits). This results in every
>> assignment needed to be cast to either uint8_t or uint16_t. With macros you
>> don't need to cast since they are typeless.

Defines without type specifier are of type "int", not typeless.

(e.g.:
---
[kaspar at localhost tmp]$ cat test.c
#include <stdio.h>

int main(){
    printf("0x%8x\n", ~0);
}
[kaspar at localhost tmp]$ gcc test.c -o test
[kaspar at localhost tmp]$ ./test
0xffffffff
[kaspar at localhost tmp]$
---

enums are mostly "int" but may be any type that fit every member of the
enum. So they behave the same when used as constants.

That means when writing to bitfields, the assignment has to be made
either through a pointer of the right size on the left hand or by using
a mask.

When stored in a struct, with defines you'd have to specify the type of
a variable holding that flag. You can do the same with enums, as Pekka
pointed out.

Kaspar


More information about the devel mailing list