Given the fact that sizeof()
operator is a compile-time operator (from this StackOverflow accepted answer) I tried to go ahead and implement a compile-time type check based on it.
What I want to achieve is compile-time check for whether or not a parameter is characters array, and if not, than raise a compilation error. My solution is based on the fact that character consume one byte. So I came up with this:
#define assert(maybeStr)\
extern int varaible_not_exist;\
if (sizeof(maybeStr[0]) != 1)\
{\
varaible_not_exist++;\
}
I figured out if sizeof(maybeStr[0])
is evaluated at compile-time, than the whole if
can be evaluated at compile-time, which means that in case the if
statement is false (maybeStr
is indeed characters array) at compile-time, the varaible_not_exist++
won't be compiled eventually, and no compilation error will be issued. And vice versa, if the if
statement is true (maybeStr
is not characters array) than varaible_not_exist++
will be compiled and compilation error will be raised.
Long story short, it seems to be working. I only tested it in online-c-compiler for now, but this macro seems to do the job.
Now, my question is whether or not this macro is solid? I mean is it possible that different compilers and different optimizations flags will yield different result?
I mean is it possible that different compilers and different optimizations flags will yield different result?
Yes, this is possible. Your code is not reliable.
If your compiler supports C11, you can use a static assertion instead:
#include <assert.h>
...
static_assert(sizeof(maybeStr[0]) == 1, "parameter must be a string");