[cfe-dev] Function pointer is compile-time constant when cast to long but not int?

Magnus Reftel magnus.reftel at gmail.com
Thu May 2 23:28:53 PDT 2013


Hi,

while trying to build some fairly low-level code from an embedded
platform, I came across a case where a function pointer was cast to
int and used in a structure initializer. Turns out clang and gcc both
reject this, but not if it's cast to long (see shell transcript
below). I realize this is undefined behaviour, but is there a reason
to handle two casts differently?

Best Regards
Magnus Reftel

$ cat fp_int.c
struct s {
        long i;
};
void f(void);
static struct s my_s = {(int)f};
$ clang -Wall -Werror -c fp_int.c -Wno-pointer-to-int-cast -Wno-unused-variable
fp_int.c:5:24: error: initializer element is not a compile-time constant
static struct s my_s = {(int)f};
                       ^~~~~~~~
1 error generated.
$ cat fp_long.c
struct s {
        long i;
};
void f(void);
static struct s my_s = {(long)f};
$ clang -Wall -Werror -c fp_long.c -Wno-pointer-to-int-cast -Wno-unused-variable
$



More information about the cfe-dev mailing list