c++ - 变量声明必须出现在最前面?

标签 c++ objective-c c

我正在查看 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/

相关文章:

c - 我不知道这个 makefile 有什么问题?

c++ - Union值的单函数比较

objective-c - Quartz2D 路径上的 3D 转换 - 绘图应用程序

objective-c - 如何使用 libstrophe 构建 jabber 客户端

ios - 以编程方式在 ios 中创建容器 View

c - 使用函数更新列表(无返回值)

c - 当程序在fclose()之前结束时会出现什么问题

c++ - 关于 C++ 中数组输出到文件的限制

c++ - 如何修复 visual studio 2012 和 VS community 2015 中的 'Access denied' 错误?

c++ - SSl 握手成功 C++