Home > Back-end >  What is the purpose of having the forward declarations in the given fragment of C code?
What is the purpose of having the forward declarations in the given fragment of C code?

Time:03-16

I have been assigned a task to maintain a legacy CGI program which adds data to a college database. This program is made up of a single file and is compiled without warnings. The file uses forward declarations as given below.

#define MAX_NAME_LEN 50

enum Grade;
enum Subject;
struct Student;
...

int lastErrorNo;

void addGrade (enum Subject subj, enum Grade g, struct Student *stud);
void editGrade (enum Subject subj, enum Grade g, struct Student *stud);
...

enum Grade {
    A = 0,
    B,
    C,
    D,
    E
};

enum Subject {
    Calculus1 = 0,
    Calculus2,
    ...
    Mechanics
};

struct Student
{
    char lastName[MAX_NAME_LEN];
    char firstName[MAX_NAME_LEN];
    ...
};

static int lastErrorNo = 0;

int main(void) {
    ...
}

void addGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
    ...
}

void editGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
    ...
}

I can't understand what is the purpose of the forward declarations of Grade, Subject, Student and lastErrNo? Why not to immediately replace them with their definitions?

CodePudding user response:

I can't understand what is the purpose of the forward declarations of Grade, Subject, Student and lastErrNo?

Abou the enums, the compiler must know the variables before you can use them, since you are using them in the functions forward declarations, the compiler needs to know what those types are.

The reason for the declaration of int lastErrorNo; globally maybe to keep as a global error flag, but since it's redeclared later as static also globally, the code won't compile due to the redeclaration, maybe a typo?

Why not to immediately replace them with their definitions?

You could just define them before you use them instead of forward declaring. It's just a matter of code organization.

  • Related