奇怪的错误 - 子程序只运行cout

Try*_*yer -2 c++ visual-studio-2010

我有以下......

int main(){

      cout<<"Before subroutine"<<endl;
      int returnvalue = subroutine();
      cout<<"After subroutine"<<endl;

}

int subroutine(){

      cout<<"Into subroutine"<<endl;
      /*subroutine does its work

        subroutine finishes its work*/
}       
Run Code Online (Sandbox Code Playgroud)

现在,上面的工作.也就是说,我可以在子程序完成后看到"After subroutine".

但是,如果我注释掉这条线

cout<<"Into subroutine"<<endl;
Run Code Online (Sandbox Code Playgroud)

subroutine(),子程序似乎没有运行.我从来没有看到"After subroutine".

这似乎是一个错误.这是一个已知问题,有哪些解决方案?

jua*_*nza 7

你有未定义的行为.该函数必须返回一个int:

int subroutine(){
  cout<<"Into subroutine"<<endl;
  return 42;
}
Run Code Online (Sandbox Code Playgroud)

另外,请确保在之前声明main():

int subroutine(); // declaration

int main()
{
  ...
}

int subroutine() { .... } // definition as before. But without bugs.
Run Code Online (Sandbox Code Playgroud)

  • @Tryer好啊,我猜你应该提到它吧. (5认同)