我正在查看 this page其中说:
In C++ you can declare variables pretty much anywhere in your program. This is not the case with C. Variables must be declared at the beginning of a function and must be declared before any other code. This includes loop counter variables, which means you can't do this:
for(int i = 0; i < 200; i++) {
Forgetting that you can't declare variables just anywhere is one of the most frequent causes of 'it won't compile' problems for programmers moving from C++ to C.
我已经使用 Objective-C 一段时间了,因此也使用了 C,我对 for(int i = 0; i < 200; i++) {
这样的语句没有任何问题。然而 Objective-C 严格来说是 C,那么这个网页指的是什么?
最佳答案
该网页对 C89 的描述不准确。
在 C89 中,您可以在任何 block 的顶部(不仅仅是在函数的开头)声明变量,但不能在 block 中的任何点声明变量。
在 C99 及更高版本中,您不必在 block 的开头声明变量。具体来说,C99 允许您编写:
for (int i = 0; i < max; i++)
如果您使用 GCC 但需要保持与 MSVC 的兼容性,那么您可以使用 -Wdeclaration-after-statement
来检测您何时在语句之后声明变量(C89 不允许这样做)。
Objective C 大概使用 C99 而不是 C89 作为它扩展的标准,因此它允许在需要时声明变量。
关于c++ - 变量声明必须出现在最前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13410744/