¿Es posible forzar la evaluación de la macro en c?

This is working, but it's kinda heavy-footed solution

#define COUNT_BITS_4b(Val) \
   ((Val) & 0x1) + (((Val) >> 1) & 0x1) + (((Val) >> 2) & 0x1) + (((Val) >> 3) & 0x1)
#define COUNT_BITS_8b(Val) \
   (COUNT_BITS_4b(Val) + COUNT_BITS_4b(Val >> 4))
#define COUNT_BITS_16b(Val) \
   (COUNT_BITS_8b(Val) + COUNT_BITS_8b(Val >> 8))
#define COUNT_BITS_32b(Val) \
   (COUNT_BITS_16b(Val) + COUNT_BITS_16b(Val >> 16))
#define COUNT_BITS_32b(Val) \
   (COUNT_BITS_16b(Val) + COUNT_BITS_16b((Val >> 31) >> 1))
....

I would like to get rid of this part, (replace it with something like this #define ULONG_BIT Eval((COUNT_BITS(ULONG_MAX)))

#if COUNT_BITS_128b(ULONG_MAX) == 32
   #define ULONG_BIT 32
#elif COUNT_BITS_128b(ULONG_MAX) == 33
   #define ULONG_BIT 33
#elif COUNT_BITS_128b(ULONG_MAX) == 34
   #define ULONG_BIT 34
....
#elif COUNT_BITS_128b(ULONG_MAX) == 128
   #define ULONG_BIT 128
#endif

Gracias por cualquier respuesta.

preguntado el 09 de marzo de 12 a las 22:03

I'm not sure what you're asking. Macros aren't "evaluated" at all. The preprocessor simply performs text substitution. -

No lo hará #define ULONG_BIT COUNT_BITS_128b(ULONG_MAX) be enough? It is a (very complex, but still) expresión constante, which any optimizing compiler would transform to a simple constant. -

@Basile Starynkevitch Will i not hit any macro size limit or something when i use ULONG_BIT defined as COUNT_BITS_128b(ULONG_MAX) in whole application ? -

@Adam Mihalcin What about #if #else statements, they have to be evaluated during compilation time. -

Oki i expanded COUNT_BITS macro to 4096 bits and used it couple of times. Looks like it will take a few minutes/hours to compile. -

1 Respuestas

If you are really looking for a way that this resolves to a decimal value at preprocessing time something like this could do the trick:

#define NEKO_4294967295 32
... for all the values up to 128 ...
... for all possible variants with U or UL appended ...
#define NEKO_TESTER(VAL) NEKO_ ## VAL
#define ULONG_BITS NEKO_TESTER(ULONG_MAX)

Although technically it is not guaranteed that ULONG_MAX resolves to a simple decimal constant.

respondido 09 mar '12, 23:03

I like the idea, but like you said standard doesn't explicitly say that ULONG_MAX have to be defined as decadic number, so basically i will have to cover all possibilities (octal and hexadecimal as well) if i want to use it. Still nice idea. - Neko

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.