Why can't a function go after Main

前端 未结 8 1840
一向
一向 2020-12-09 12:37

Why can\'t I put a function after main, visual studio cannot build the program. Is this a C++ quirk or a Visual Studio quirk?

eg.

int main()
{
   myF         


        
相关标签:
8条回答
  • 2020-12-09 12:50

    You can, but you have to declare it beforehand:

    void myFunction(); // declaration
    
    int main()
    {
       myFunction();
    }
    
    void myFunction(){} // definition
    

    Note that a function needs a return type. If the function does not return anything, that type must be void.

    0 讨论(0)
  • 2020-12-09 12:50

    Functions need to be declared before they can be used:

    void myFunction();
    
    int main() {
      myFunction();
    }
    
    void myFunction() {
      ...
    }
    
    0 讨论(0)
  • 2020-12-09 12:55

    You cannot use a name/symbol which is not yet declared. That is the whole reason.

    It is like this:

    i = 10;  //i not yet declared
    
    int i;
    

    That is wrong too, exactly for the same reason. The compiler doesn't know what i is – it doesn't really care what it will be.

    Just like you write this (which also makes sense to you as well as the compiler):

    int i;  //declaration (and definition too!)
    
    i = 10;  //use
    

    you've to write this:

    void myFunction(); //declaration!
    
    int main()
    {
       myFunction() //use
    }
    
    void myFunction(){}  //definition
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-09 12:57

    most of the computer programming languages have top to down approach which means code is compiled from the top. When we define a function after main function and use it in the main [myFunction () ], compiler thinks " what is this. I never saw this before " and it generates an error saying myFunction not declared. If you want to use in this way you should give a prototype for that function before you define main function. But some compilers accept without a prototype.

    #include<stdio.h>
    void myFunction(); //prototype
    int main()
    {
       myFunction(); //use 
    }
    
    myFunction(){ //definition 
    .......;
    }
    
    0 讨论(0)
  • 2020-12-09 13:03

    specify the function declaration before calling function .So that compiler will know about return type and signature

    0 讨论(0)
  • 2020-12-09 13:08

    Because

    myFunction()
    

    has to be declared before using it. This is c++ behaviour in general.

    0 讨论(0)
提交回复
热议问题