[SOLVED] How to properly write a struct

Issue

I have seen some programmers code looking as below

Where after they have declared a struct they have two similar function pointing to the struct

What is the porpouse of the first void Point_print(const struct screen* self);
when below of the main function there is another void Point_print(const struct screen* self); doing all the expressions

struct screen{
    double x;
    double y;
};

void Point_print(const struct screen* self); // <-- what is the purpose of having this function?



int main(int argc, const char * argv[]) {
    
    struct screen aScreen;
    aScreen.x = 1.0;
    aScreen.y = 2.0;
    
    Point_print(&aScreen);
    return 0;
}

void Point_print(const struct screen * self){ // <-- this function is doing the work?
    printf("x:%f, y:%f",(*self).x,(*self).y);
}


Solution

// this is called function signature or declaration, 
// and typically it's what's found in
// header files, this is all that's needed to properly generate the code
// to call this function.

void Point_print(const struct screen* self); // <-- what is the purpose of having this function?

Now that it’s declared you can use it:

int main(int argc, const char * argv[]) {
    
    struct screen aScreen;
    aScreen.x = 1.0;
    aScreen.y = 2.0;
    
    Point_print(&aScreen); // <--- it's the use here
    return 0;
}

This is the function body or implementation:

void Point_print(const struct screen * self){ // <-- this function is doing the work?
    printf("x:%f, y:%f",(*self).x,(*self).y);
}

When the linking step occurs it resolves the "link" between the "calling points" and where the actual body of the function.

One way to experience is to comment out the function body part completely and try compiling the file with main in it, it will compile correctly, however will spew out linking error.

Answered By – Ahmed Masud

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.