Size of the preprocessor value size_t

I am creating a hash table implementation in C for educational purposes.

The hash function must return the hash size size_t. Since the size_t size differs on different platforms (and I want to use a hash function that hashes all the bits in size_t), I thought about creating different hash functions for different sizes. Since the hash function will be used as a function pointer, I suspect the compiler cannot inline the code like this:

size_t hash4(void* key, size_t size);
size_t hash8(void* key, size_t size);

size_t hash(void* key, size_t size)
{
    if (sizeof(size_t) == 4)
    {
        return hash4(key, size);
    }
    else if (sizeof(size_t) == 8)
    {
        return hash8(ket, size);
    }
}

size_t (*hashFunc)(void* key, size_t size) = hash;

      

And two levels of indirection will be used every time the hash function is called.

That's why I thought to do something like this: size_t (*hashFunc)(void* key, size_t size) = hash##sizeof(size_t);

. Only one level of indirection will be used. The problem is that the sizeof operator is not available during the prepositioning phase.

So what would be a good way to define a preprocessor value that will expand to the correct size_t size on each platform? I think I could test the predefined macros, but I'm wondering if there is a better way.

+3


source to share


3 answers


You can do it:

size_t (*hashFunc)(void* key, size_t size) = (sizeof(size_t) == 8) ? hash8 : hash4;

      



There is nothing wrong with eznme either - write one function that behaves differently according to the size size_t

. Of course, you don't need the function hash4

for other purposes in 64-bit implementations.

As for the title of the question - if you need to know about size_t

during preprocessor use the macro SIZE_MAX

from stdint.h

.

+1


source


sizeof

is a C operator. ##

is a preprocessor operator. The latter knows nothing about the former.

So you might be better off using a macro that referencing the system's bit-widths used for addressing, like testing for example:



#if UINTPTR_MAX == 0xffffffffffffffff
/* it 64bits pointers */
#elif UINTPTR_MAX == 0xffffffff
/* it 32bits pointers */
#endif

      

+3


source


Use 64-bit detection macro defined for many compilers, eg. GCC uses__x86_64

size_t hash(void* key, size_t size) {
   #ifdef __x86_64
       compute 64bit hash
   #else
       compute 32bit hash
   #endif
}

      

+2


source







All Articles