Functino
Functino

Reputation: 1935

Will a cast ever fail in C?

Specifically, my question is, given this macro:

#define FAKE_VAL(type) ((type)0)

...is there any value of type (including structures, function pointers, etc.) where FAKE_VAL(type) will cause a compile-time error?

I'm asking because I have a macro that take a function pointer as an argument, and needs to find the size of its return value. I know the types and number of arguments the function pointer takes, so I'm planning to write something like:

sizeof(fptr(FAKE_VAL(arg_type_1), FAKE_VAL(arg_type_2)))

arg_type_1 and 2 could be literally anything.

Upvotes: 2

Views: 991

Answers (4)

atamit81
atamit81

Reputation: 227

typecast is used to inform the compiler that the programmer has already considered the side effects of using the variable in a different way than it was declared as. This causes the compiler to switch off its checks. So with typecasts you wont get warnings/errors.
Yeah. it does type conversion of any type to the typecasted one. My bad. But this can cause segmentation faults/errors when the program is actually run.

Upvotes: -1

Jens Gustedt
Jens Gustedt

Reputation: 78993

To give it a more systematic answer. In C cast are only allowed for arithmetic and pointer types. So anything that is a struct, union or array type would lead to a compile time error.

Upvotes: 0

user2357112
user2357112

Reputation: 282042

You can't cast an int to an array type, so

FAKE_VAL(int[5]);

will fail. Try it!

Upvotes: 2

John3136
John3136

Reputation: 29266

Of course there is.

struct fred (i.e. not a pointer) - how do you convert 0 (scalar type) to a struct (non scalar type)? Any literal value FAKE_VAL("hi") gives (("hi")0) - what does that mean?

Upvotes: 3

Related Questions