为什么函数只能在其他函数内部调用

Why can functions only be called inside other functions?

本文关键字:函数 内部 调用 其他 为什么      更新时间:2023-10-16
....
void foo()
{}
...
foo(); //why we can not call the function here?
int main(int argc, char** argv)
{}

我知道你不能这样做,它会导致编译器错误。我想这可能与某些编译器理论有关,但任何人都可以告诉我它的本质,还是只是一个任意规则?

当我尝试编译以下代码时:

#include<iostream>
using namespace std;   
void foo()
{
    cout<<"test"<<endl;
}   
foo();    
int main() {}

我收到此错误消息。

test.cpp:10:6:错误:在";"令牌之前进行预期的构造函数、析构函数或类型转换

为什么我会收到此错误?

你的假设是错误的。

#include <iostream>
int foo() {
  std::cout << "outside main" << std::endl;
  return 0;
}
int Global = foo();
int main() {
  std::cout << "intside main" << std::endl;
  return 0;
}

现在正式规则:函数调用是一个表达式。表达式可能出现在语句中,语句可能出现在函数中。但表达式也可能出现在其他上下文中,例如全局对象的初始化 - int Global上面。