Defining and Declaring a C++ Function



One of the rules of the C/C++ language is the following, and we know it very well for variables: Any identifier, in order to be used, must first be declared. This rule also applies to functions, so we identify the following notions, seemingly similar. Understanding them well will save us from many errors!!



Let's consider the following example, without practical significance:

#include < iostream >
using namespace std;

void F(){
    cout << "Hello";
}

int main()
{
    F();
    return 0;
}

The program is syntactically correct. The part:

void F()
{
   cout << "Hello";
}

represents the definition of the function F(), but here it also gets declared. If we change the order of functions F() and main(), we get:

#include < iostream >
using namespace std;

int main()
{
    F();
    return 0;
}

void F()
{
    cout << "Hello";
}

This time the program is not correct. We notice that the identifier F is not declared. It can be declared by specifying the function prototype before the main() function (practically, before calling it), as below:

#include < iostream >
using namespace std;

void F();

int main()
{
    F();
    return 0;
}

void F()
{
    cout << "Hello";
}

We observe that the prototype (declaration) is a regular C++ statement, which ends with a ; !!


Color Contrast

Text Size

Text Spacing

Reading Aids


In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!


Summary

In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!


Chatbot