Oh Oh
Oh Oh

Reputation: 35

Why does where you declare function matter?

So im just learning C but from my understand we can create Function Prototypes anywhere right?

So then when i was experimenting with function and structure why is it that. If i put the function prototype before the structure declaration is does not work but when i put the function prototype after the structure declaration it does work ?.

Could some kind soul explain this?

Before structure declaration (Does not Work)

/* Function Prototypes */
void printID(struct studentID person);

/* Structure Decleration */
struct studentID{
    char Name[50];
    int Age;
    int Birth_Year;
};


int main(){
    struct studentID me = {"BOB", 25, 1996};
    printID(me);
    return 0;
}

/* Function Details */
void printID(struct studentID person){
    printf("Your Name is %s\n", person.Name);
    printf("Your Age is %d\n", person.Age);
    printf("Your date of birth is %d\n", person.Birth_Year);
}

After Structure declaration (Does Work)

/* Structure Decleration */
struct studentID{
    char Name[50];
    int Age;
    int Birth_Year;
};

/* Function Prototypes */
void printID(struct studentID person);

int main(){
    struct studentID me = {"BOB", 25, 1996};
    printID(me);
    return 0;
}

/* Function Details */
void printID(struct studentID person){
    printf("Your Name is %s\n", person.Name);
    printf("Your Age is %d\n", person.Age);
    printf("Your date of birth is %d\n", person.Birth_Year);
}

Upvotes: 1

Views: 49

Answers (1)

John Bode
John Bode

Reputation: 123558

Data types must be defined before you can use them.

Since printID has a parameter of type struct studentID, the definition of struct studentID must come before the declaration of printID.

C compilers process files in a single pass, so all types must be defined before they can be used, and all functions must be at least declared before they can be called.

A type definition must be complete before you can create an instance (object) of that type. For struct, union, and enum types, the type definition isn’t complete until the closing }.

However, you can declare pointers to incomplete types; IOW, the following would be perfectly legal:

struct studentID;  // incomplete type definition

void printID( struct studentID *person ); 

struct studentID {
  ...
}; // type definition is now complete

You would still need the definition of struct studentID to be complete before you could dereference it in the body of printID, so you would have to put the body of printID after this.

Upvotes: 2

Related Questions