0

Consider the following,

void doNothing(int,int); // Only declared

int main(){
    int x; // Both defined and declared
    return 0;
}

Why is it that when a function prototype is declared, it is not also instantiated in memory, but variable x is?

I understand clearly the difference between a definition and a declaration, I just want to know why it is C++ chooses not to instantiate the function prototype, while it does choose to instantiate variable x which in this example, also holds no value.

cigien
  • 50,328
  • 7
  • 37
  • 78
Euphoria
  • 77
  • 7
  • 1
    A function has to have a body. No body nothing to instantiate. – doug Oct 18 '20 at 05:50
  • Because there isn't anything that needs to be put in memory to represent a function prototype; it's only a heads-up to the compiler so that it knows what the function name means when it's seen later on. The variable will conceptually take up space, because memory is used to keep track of the value stored in that variable. – Karl Knechtel Oct 18 '20 at 05:50
  • In reference to doug, I would assume that there is also nothing to instantiate in variable x as it holds no value, the same as doNothing(). In reference to Karl, does that mean it is done out of optimization purposes? – Euphoria Oct 18 '20 at 05:52
  • Please don't edit the title to say it's not a duplicate. Just add text to the answer as you've done. Can you clarify what you mean by *instantiate*? – cigien Oct 18 '20 at 06:01
  • Instantiation relating to it being given a place in memory. It seems to be explained that the prototype remains uninstantiated as there is no body and no value to hold for the function prototype, so why is it that variable x would be instantiated with a place in memory when it also is holding no value? Considering x has not been initialized, it cannot be used in its current form in this specific example, so I would think it should also remain uninstantiated. – Euphoria Oct 18 '20 at 06:04
  • But `x` *is* holding a value. It's an indeterminate value, and can't be read from, but it's still a value. – cigien Oct 18 '20 at 06:06
  • Understood, so why would the function prototype not also hold an indeterminate value? Why is it choosing to put x in memory as an object and not the function prototype? – Euphoria Oct 18 '20 at 06:07
  • Because a function doesn't have a value. It's just a computation. – cigien Oct 18 '20 at 06:12
  • That makes more sense, thank you!!! I apologize if my question came across as confusing in the context of what I was trying to ask. – Euphoria Oct 18 '20 at 06:16
  • No problem :) It's just that *instantiation* has a very specific meaning in c++, and I was pretty sure you didn't mean that, so I was asking for clarification. – cigien Oct 18 '20 at 06:21
  • As for `x`, it may not have a value but it can be written to therefor it has to have space reserved for it. – doug Oct 19 '20 at 00:21

0 Answers0