Can anyone give a simple code to explain the statement"a funtion ca have multiple declaration but only one definition"?

void foo(void); // Declaration
void foo(void); // Declaration (redundant but legal)

void foo(void) {} // Definition
void foo(void) {} // Definition (redundant and illegal)

A function definition is where you give the function a body. A declaration has no body and only lists the function signature (return type, name, and parameters). So the statement could be simplified to "a function can only have one body".

commented: thankyou for your simple explanation +0

It is actually a very useful feature. You can declare function prototypes multiple ways (very necessary when using template functions) ie

adduser(str name, int age, char sex, float height_in_inches)
adduser(str name, int age)

In this way, you can declare default values for the unused variables, and allow the function to be called with certain parameters as "not necessary"

if you were to define a function multiple ways

adduser(str name, int age)
{
printf("%d",age);
}

adduser(str name, int age)
{
printf("oops");
}

The program and compiler would have no idea what to do. Similar analogy, A square is a rectangle by defination, however a rectangle is not a square. This is kinda a prelim intro into inheritance, which is prevelant in C++

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.