Can we have functions inside functions in C++?

后端 未结 12 2311
抹茶落季
抹茶落季 2020-11-22 14:51

I mean something like:

int main() 
{
  void a() 
  {
      // code
  }
  a();

  return 0;
}
12条回答
  •  甜味超标
    2020-11-22 15:26

    But we can declare a function inside main():

    int main()
    {
        void a();
    }
    

    Although the syntax is correct, sometimes it can lead to the "Most vexing parse":

    #include 
    
    
    struct U
    {
        U() : val(0) {}
        U(int val) : val(val) {}
    
        int val;
    };
    
    struct V
    {
        V(U a, U b)
        {
            std::cout << "V(" << a.val << ", " << b.val << ");\n";
        }
        ~V()
        {
            std::cout << "~V();\n";
        }
    };
    
    int main()
    {
        int five = 5;
        V v(U(five), U());
    }
    

    => no program output.

    (Only Clang warning after compilation).

    C++'s most vexing parse again

提交回复
热议问题