为什么必须在函数中包含c ++代码? [英] Why must c++ code be contained within functions?

查看:97
本文介绍了为什么必须在函数中包含c ++代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为c ++的新手,来自python,我不知道为什么c ++不允许函数之外的代码(在全局命名空间?)。似乎这可能是有用的,在main()被调用或其他函数甚至声明之前做一些初始化。 (我不想与编译器争论,我只是想知道这种方式实现它的思想过程。)

As a newbie to c++, coming from python, I'm not sure why c++ doesn't allow code outside of a function (in the global namespace?). It seems like this could be useful to do some initialization before main() is called or other functions are even declared. (I'm not trying to argue with the compiler, I'd just like to know the thought process behind implementing it this way.)

推荐答案

当你运行一个python程序,解释器运行通过它从上到下执行。在C ++中,这不会发生。编译器将所有函数构建成小块的机器代码,然后链接器将它们挂接起来。在运行时,操作系统调用 main 函数,一切都从那里开始。在这种情况下,函数之外的代码是无意义的 - 它什么时候运行?

When you're running a python program, the interpreter runs through it from top to bottom executing as it goes. In C++, that doesn't happen. The compiler builds all your functions into little blobs of machine code and then the linker hooks them up. At runtime, the operating system calls your main function, and everything goes on from there. In that context, code outside of functions is meaningless - when would it run?

这篇关于为什么必须在函数中包含c ++代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆