UFO Project question

I am confused by the line of code sitting at the top of ufo.hpp

void display(int misses);

There appears to be no traditional body to this function, nothing within brackets, so I don’t understand what it is actually doing or how it works. Thanks.

Hello :slight_smile:

Ok, let me start by answering your question (convenient, right?). This line:

void display(int misses);

is a function declaration. You can read more about function declarations for example here -> https://www.studytonight.com/cpp/functions-in-cpp.php (section Declaring, Defining and Calling a Function).

Short version - this function declaration tells your computer that function display will be later defined, this function will return a void value (so it will return nothing) and expects one int parameter. Your computer now knows that this function will be defined later in the code, but you can use this function right away!

Ok, I know, this does not sound that exciting that it would require an exclamation mark. I will show you an example where this might be useful. Take a look at this code -> https://repl.it/@factoradic/Circular-dependency. These two functions are written badly on purpose. What is important is that in the body of the function odd there is a call to function even and in the body of the function even there is a call to function odd. In programming, this is called a circular dependency (nice Wikipedia article, worth reading). And this code would not be possible without function declarations.

You may wonder if we could just move function definitions to the top of the file and delete function declarations, something like this:

#include <iostream>

void odd(int x) {
    if ((x % 2) != 0) {
        std::cout << "It is odd.\n";
    } else {

void even(int x) {
    if ((x % 2) == 0) {
        std::cout << "It is even.\n";
    } else {

int main() {
    int i;
    do {
        std::cout << "Please, enter number (0 to exit): ";
            std::cin >> i;
        } while (i != 0);

    return 0;

answer is… nope. This will result in main.cpp:7:9: error: use of undeclared identifier 'even' error, if we would change the order of the functions the error would be main.cpp:7:9: error: use of undeclared identifier 'odd'.

I hope that now you know that function declarations might be useful. Later you will find more uses for them (separation in the files etc.), but for now, this should be more than enough :slight_smile:


Thank you for the great reply and resources!

I have a much better understanding now. I don’t fully get it all yet, but I think as I progress more through C++ with different cases it will become more clear to me. But I do understand the basic premise of what you explained. I’m glad I asked, thanks so much.

You’re very welcome :panda_face:

I am sure it will. And if some concepts will be very problematic, we will be here ready to help :slight_smile: