Search code examples
c++function-prototypes

Function prototype confusion


i have been learning C++ for a while and the only thing i cannot wrap my head around at all is the function prototype and function call and function definition stuff. Ive read all sorts of stuff and still have no clue what it means or does. i just want to be able to understand and identify each of those. i am pretty sure that these are important to programming from what i have read.i have a rough idea of a function prototype, i believe it is a statement tat returns the value of something.


Solution

  • Let me see if I can explain with some analogies

    Function Prototype - It is like an ad for a product - It says there is a Product X and you can get it from Location Y. This is sufficient for you as a consumer, but doesnt say anything about what goes on behind the scenes to get X to Y and to you.

    Similarly, a function prototype is a statement that just says that there is a function somewhr that is named X, takes arguements Y and returns value Z. Enough for any callers but cant do anything on its own.
    e.g int DoSomething(int arg);

    Function Call - This is the consumer going and asking for the product X at location Y.

    This is when the function code is actually called. But to be able to call the function you need to know it exists, so you need(at least) a prototype for the function just above the call.
    e.g int a = DoSomething(1);

    Function Definition - This is the actual procedure that manufactures product X and transports it to location Y.

    Essentially this is the code of the function itself.
    e.g
    int DoSomething(int arg){
    return arg+2;
    }

    A function prototype(also called forward declaration) is needed in C and for free functions (functions which do not belong to a class) in C++