4

Assume this code:

#include <stdio.h>

int a(){
 int b = 5;
 return b;
}

int main ()
{
  printf("%d\n", sizeof(a));
  return 0;
}

Above prints 1. What does that mean?

I know when sizeof is used on a struct, it gets the total size of the data types within it in bytes. But what does it mean when it's used on a function?

Edit:

What if I do sizeof(a())) instead of sizeof(a)). Now it's printing 4 which is the size of the return type, is this the correct way? how is it not undefined?

1 Answers1

3

Applying the sizeof operator to a function is a constraint violation. Doing so invokes undefined behavior.

This constraint is specified in section 6.5.3.4p1 of the C standard regarding the sizeof operator:

The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member. The _Alignof operator shall not be applied to a function type or an incomplete type.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
dbush
  • 205,898
  • 23
  • 218
  • 273
  • What if I do `sizeof(a()))` instead of `sizeof(a))`. Now it's printing `4` which is the size of the return type, is this the correct way? how is it not undefined? –  Apr 21 '20 at 14:20
  • 1
    @Alex `sizeof(a()))` is valid because `a()` has type `int` which is the return type of the function. *"is this the correct way?"* to do what? – dbush Apr 21 '20 at 14:23
  • printing `size_t` with `%d` also invokes UB. `%p` must be used instead – phuclv Apr 21 '20 at 14:26
  • @phuclv `%p` is for pointers. `%zu` is for `size_t`. – dbush Apr 21 '20 at 14:32
  • @dbush yeah, I mistyped `%p` instead of `%zu` – phuclv Apr 21 '20 at 14:33