Domanda

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.

È stato utile?

Soluzione

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++

Altri suggerimenti

A function prototype is unique to C -- not used in C++. A C function prototype is mostly equivalent to a C++ function declaration, such as:

int f(int);
int g(double);

The place they differ is if you don't put anything in the parentheses:

int f();

In C++, this declares f as a function that takes on arguments. In C, it declares f as a function without specifying anything about the arguments1. To get a C prototype that's equivalent to the C declaration, you need to put something between the parentheses:

int f(void);

The latter is also allowed in C++, but most C++ programmers prefer to avoid it.

A function definition is where you have the header and body of a function:

int f(int x) {
    return x+4;
}

A function call is where you use a function you've defined:

int y = 2;

int x = f(y); // using the f() above, this is equivalent to int x = 6;

1 Back in the olden days (before about 1985 or so) C didn't have function prototypes at all, so this was the only sort of function declaration that was supported. It's generally frowned upon in new code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top