1

I have a function as below:

int fun()
{
    puts("hello");
    return 10;
}

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

I want to ask why when I call sizeof(fun()) it just return size of int. and why puts in func() function don't show out in screen.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Hồng Phúc
  • 408
  • 3
  • 10
  • What do you expect `sizeof` to give you? – NathanOliver Mar 12 '19 at 13:25
  • 2
    https://stackoverflow.com/questions/8225776/why-does-sizeofx-not-increment-x?rq=1 – Öö Tiib Mar 12 '19 at 13:26
  • 3
    Note that the `sizeof` operator returns a value of type `size_t`. The correct `printf` format specifier for `size_t` is e.g. `"%zu"`, and definitely *not* `"%d"`. Mismatching format specifier and argument type is *undefined behavior*. – Some programmer dude Mar 12 '19 at 13:27
  • sizeof is interpreted at compile time ... it just return the size of the return type of fun, that is int. It does not call fun at all – Gojita Mar 12 '19 at 13:29
  • *"why when I call sizeof(fun()) it just return size of int"* You didn't ask for the size of `fun`, you asked for the size of the result of calling `fun` with no arguments, and the result is `int`. Size of `fun` would be `sizeof fun` (which doesn't compile, since functions don't have sizes in C++). – HolyBlackCat Mar 12 '19 at 13:29
  • The expression inside `sizeof(...)` is unevaluated context, the function won't be called. It will only evaluate the size of the return type. – Guillaume Racicot Mar 12 '19 at 13:30

0 Answers0