0
void f(){}
  int main(){
  printf("%d",sizeof(f()));
  return 0;
  }

This displays "1" in gcc, and "0" in VC . Why?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
fredzzt
  • 11
  • 1
  • You are using sizeof on `f()` and not a pointer to `f`, this might be the problem ? – Eregrith Jun 19 '14 at 14:39
  • 4
    Note that using [sizeof on a function is undefined behavior](http://stackoverflow.com/a/19906869/1708801). – Shafik Yaghmour Jun 19 '14 at 14:40
  • I think question should closed better with the link provided by @ShafikYaghmour. But [Grijesh's answer](http://stackoverflow.com/a/14909202/2455888) there explained it well. – haccks Jun 19 '14 at 14:43
  • 1
    This doesn't compute the size of the function, it computes the size of the function's result, which is of type `void`. `void` has no size, so the expression is invalid in standard C. GCC has an extension (an ill-advised one in my opinion) that causes it to treat `sizeof (void)` as 1 (to permit pointer arithmetic on `void*`). I'm less familiar with VC, but apparently it also has some non-standard extension. – Keith Thompson Jun 19 '14 at 15:07
  • To compute the size of a function, you'd write `sizeof f`, but that's also invalid; functions are not objects, and that don't have sizes. – Keith Thompson Jun 19 '14 at 15:09
  • @ShafikYaghmour: It's not merely undefined behavior, it's a constraint violation. – Keith Thompson Jun 19 '14 at 15:10
  • Also do not print the result of `sizeof` with `%d`. It's a `size_t` and should be printed with `%zu`. – Pascal Cuoq Jun 19 '14 at 17:23
  • @KeithThompson can you point me to a good reference on how contraints are related to undefined behavior? I found [this](https://groups.google.com/forum/#!topic/comp.std.c/WNVXRSCqrGU) but I wonder if there is not something more concise. – Shafik Yaghmour Jun 20 '14 at 14:25
  • 1
    [N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) is the latest draft of the standard. 5.1.1.3 says that a conforming compiler must produce a diagnostic for any violation of a constraint or syntax rule. If that diagnostic is a warning rather than a fatal error, and the compiler produces an executable, its behavior is undefined. If the diagnostic is fatal, then there is no (run-time) behavior. (This isn't easy to infer from the wording of the standard, which IMHO could be a lot clearer.) – Keith Thompson Jun 20 '14 at 14:52

0 Answers0