-1

Possible Duplicate:
Why is the size of a function in C always 1 byte?

Consider the below code snippet in C:

double fn()
{
    return 1.1 ;
}

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

The output is:

1

Why the sizeof() operator is outputting 1 byte?

Community
  • 1
  • 1
Green goblin
  • 9,898
  • 13
  • 71
  • 100

2 Answers2

4

The sizeof operator should not be applied to a function. It is meaningless and its behaviour is not defined.

The size operator shall not be applied to an expression that has function or incomplete type,...

Reference: ISO/IEC 14882 (section 5.3.3)


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.

Reference: ISO/IEC 9899:1999 (section 6.5.3.4)


The sizeof operator may not be applied to:

  • A bit field
  • A function type
  • An undefined structure or class
  • An incomplete type (such as void)

Reference: http://publib.boulder.ibm.com/

ronalchn
  • 12,225
  • 10
  • 51
  • 61
  • That's only a reference for one compiler however, I wouldn't trust it as the defining source for all compilers. – Richard J. Ross III Sep 08 '12 at 00:12
  • That's only because it takes me a while to find all the references and that was the first I found. I already knew the answer, just wanted to publish it earlier before all information was found. – ronalchn Sep 08 '12 at 00:19
2

When you use sizeof on a function, it's value is meaningless, as described here Why is the size of a function in C always 1 byte?

To get the size of the return value, try using sizeof(fn()), because sizeof is a compile-time constant (in most scenarios), fn will not really be called, however.

To get the size that the function takes up in bytes, however, is not possible to do portably, unfortunately. If you told us what you really wanted to accomplish, we could probably help you do more.

Community
  • 1
  • 1
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201