C equivalent size for macros

So, I am optimizing some code by unrolling some loops (yes, I know that I have to rely on my compiler to do this for me, but I do not work with my choice of compilers), and I wanted to do it a little elegantly, so , in case of data resizing due to some changes in the future, the code will degrade elegantly.

Sort of:

typedef struct {
    uint32_t alpha;
    uint32_t two;
    uint32_t iii;
} Entry;

/*...*/

uint8_t * bytes = (uint8_t *) entry;
#define PROCESS_ENTRY(i) bytes[i] ^= 1; /*...etc, etc, */ 
#if (sizeof(Entry) == 12)
    PROCESS_ENTRY( 0);PROCESS_ENTRY( 1);PROCESS_ENTRY( 2);
    PROCESS_ENTRY( 3);PROCESS_ENTRY( 4);PROCESS_ENTRY( 5);
    PROCESS_ENTRY( 6);PROCESS_ENTRY( 7);PROCESS_ENTRY( 8);
    PROCESS_ENTRY( 9);PROCESS_ENTRY(10);PROCESS_ENTRY(11);
#else
#   warning Using non-optimized code
    size_t i;
    for (i = 0; i < sizeof(Entry); i++)
    {
        PROCESS_ENTRY(i);
    }
#endif
#undef PROCESS_ENTRY

This does not work, of course, as it is sizeofnot available to the pre-processor (at least what this answer seemed to indicate).

Is there an easy workaround that you can use to get the data structure sizeofto use with the C macro, or am I just SOL?

+5
6

, . if :

#define PROCESS_ENTRY(i) bytes[i] ^= 1; /*...etc, etc, */ 
if (sizeof(Entry) == 12) {
    PROCESS_ENTRY( 0);PROCESS_ENTRY( 1);PROCESS_ENTRY( 2);
    PROCESS_ENTRY( 3);PROCESS_ENTRY( 4);PROCESS_ENTRY( 5);
    PROCESS_ENTRY( 6);PROCESS_ENTRY( 7);PROCESS_ENTRY( 8);
    PROCESS_ENTRY( 9);PROCESS_ENTRY(10);PROCESS_ENTRY(11);
} else {
    size_t i;
    for (i = 0; i < sizeof(Entry); i++) {
        PROCESS_ENTRY(i);
    }
}

sizeof , . C , - . #warning.

+17

autoconf , (, #define SIZEOF_Entry 12). , - .., , .

, .

+9

- , , - .

#define , , , , .

if (sizeof(Entry) == 12) , . .

+5

, , , ++, , :

template <std::size_t SizeOfEntry>
void process_entry_loop(...)
{
    // ... the nonoptimized version of the loop
}

template <>
void process_entry_loop<12>(...)
{
    // ... the optimized version of the loop
}

// ...

process_entry_loop<sizeof(Entry)>(...);
+1

spring - , Duff .

+1

If you want the smallest possible size for the structure (or align it with a 4-byte border or something else), you can use packed or aligned attributes.

In Visual C ++, you can use # pragma pack , and in GCC you can use __attribute __ ((packed)) and __attribute __ ((aligned (Num byte)).

-1
source

All Articles