memoryallocator
memoryallocator

Reputation: 25

Find out if a typedef defines a specific type in C

I have to implement a linked list data structure in C. In "linked_list.h" header file I have the following line:

typedef int ListDataType;

My question is, how can I terminate the program if ListDataType is not equal to int? I know that the preprocessor can't prevent my program from compiling in case this requirement is not met (because it knows nothing about typedefs).

I code in C11, and I know about _Generic keyword. How can I avoid writing such things as the following?

{
  ListDataType q;
  const bool kListDataTypeIsNotInt = _Generic(q, int: false, default: true);
  if (kListDataTypeIsNotInt) {
    print_error_message_and_exit("list data types other than int are not supported");
  }
}

Should I use the macro (#define LIST_DATA_TYPE int) instead?

Upvotes: 0

Views: 104

Answers (1)

Lundin
Lundin

Reputation: 213689

The variable in your code will get optimized away and I strongly suspect this code will be 100% compile-time after optimizations.

Still, if you are uncertain, you could tweak it ever so slightly by introducing a macro and a static assertion:

#define IS_INT(q) _Generic((q), int: true, default: false)
...

ListDataType q;
_Static_assert(IS_INT(q), "list data types other than int are not supported");

This is 100% compile-time and good practice.

Upvotes: 1

Related Questions