0

I have read that using a function name without () gives the address, and that & is optional. However, with the sizeof operator it apparently isn't optional.

void someFunction(void) { }
printf("%ld\n",sizeof(someFunction));
printf("%ld\n",sizeof(&someFunction));

Prints 1 and 8. With warnings on, gcc and clang give a [-Wpointer-arith] warning on the first version:

warning: invalid application of 'sizeof' to a function type [-Wpointer-arith]
Scooter
  • 6,802
  • 8
  • 41
  • 64
  • 2
    `someFunction` has _function type_ and cannot legally be operated on by `sizeof`. `&someFunction` has a _pointer type_ derived from the function type. Like all pointer types, it is an _object type_, and can be operated on by `sizeof`. – Ian Abbott Mar 28 '17 at 16:10
  • It's not an _exact_ dupllicate of the other question, as that does not deal with `sizeof(&function)`. – Ian Abbott Mar 28 '17 at 16:13
  • 3
    Note that the result of `sizeof` has `size_t`, which must be printed with a `%zu` format. – Jens Mar 28 '17 at 18:35
  • @IanAbbott But it appears that most of the time the compiler sees a function name without () and substitutes the address of the function, so I don't understand why it does not substitute when it is the argument to sizeof(). – Scooter Mar 28 '17 at 21:44
  • @Jens OK, thanks for the info. I am surprised that neither clang or gcc gives a warning for that (with full warnings on). At least I think I used a compiler once that would warn on printf mismatches. – Scooter Mar 28 '17 at 21:50
  • 1
    C has some magic where a pointer to a function decays to a function during a function call (so if you have a function pointer `foo`, this lets you replace `(*foo)(params)` with `foo(params)`), and it can automatically convert a function to a function pointer when necessary (in fact for a function call, the function is converted to a function pointer). However, that magic does not apply to the `sizeof` operator. It can operate on a (data) object, or on a (data) object type within parantheses, but cannot operate on a function, nor on a function type within parentheses. – Ian Abbott Mar 29 '17 at 14:23

0 Answers0