Computer Science, asked by tdprajapati7912, 11 months ago

Once function is defined it can be called any where in c ?

Answers

Answered by dorgan399
1

presume that you mean the main function. Yes, we can define classes (including structs) after main function. A demo:

int main(){}

struct S{};

When we define functions, we can declare the function before the main program and then write the function definition after the main program. I wanted to know if we can do something similar to this when defining structures.

Same applies to classes, you can (forward) declare them before a function, and define after. However, the uses of an incomplete (declared but not defined) classes are quite limited. You can define pointers and references to them, but you cannot create them, or call any member functions. A demo:

struct S;     // (forward) declaration of a class

S* factory(); // (forward) declaration of a function

int main(){

   S* s = factory(); // OK, no definition required

   // s->foo();      // not OK, S is incomplete

   // S s2;          // not OK

}

struct S{             // definition of a class

   void foo();       // declaration of a member function

};

S* factory() {

    static S s;      // OK, S is complete

    s.foo();         // OK, note how the member function can be called

                     // before it is defined, just like free functions

    return &s;

}

void S::foo() {}      // definition of a member function

Similar questions