变量声明必须出现在前面吗?

时间:2021-10-26 11:30:34

I'm looking at this page which says:

我在看这页上面写着:

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:

在c++中,几乎可以在程序的任何地方声明变量。C.变量必须在函数的开头声明,并且必须在任何其他代码之前声明。这包括循环计数器变量,这意味着您不能这样做:

for(int i = 0; i < 200; i++) {

for(int i = 0;我< 200;我+ +){

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.

对于从c++迁移到C的程序员来说,忘记不能在任何地方声明变量是导致“它不会编译”问题的最常见原因之一。

I've been using Objective-C for a while, and thus C, and I have no problems with a statement such as for(int i = 0; i < 200; i++) { and yet Objective-C is C, strictly, so what is this web page referring to?

我使用Objective-C已经有一段时间了,因此C,对于for(int I = 0;我< 200;但是Objective-C严格来说是C,那么这个网页指的是什么呢?

1 个解决方案

#1


6  

The web page is inaccurately characterizing C89.

web页面对C89的描述不准确。

In C89, you could declare variables at the top of any block (not just at the start of a function), but not at any point during a block.

在C89中,您可以在任何块的顶部声明变量(不只是在函数的开头),但不能在块的任何位置声明变量。

In C99 and beyond, you are not constrained to declare variables at the beginning of a block. Specifically, C99 allows you to write:

在C99和beyond中,您不必在块的开头声明变量。具体来说,C99允许你写:

for (int i = 0; i < max; i++)

If you use GCC but need to retain compatibility with MSVC, then you can use -Wdeclaration-after-statement to detect when you declare a variable after a statement (which C89 does not allow).

如果您使用GCC但需要保持与MSVC的兼容性,那么您可以使用- wdeclaration - afterstatement来检测在语句之后(C89不允许)声明变量的时间。

Objective C presumably uses C99 rather than C89 as the standard it extends, so it allows variable declarations when needed.

Objective C使用C99而不是C89作为标准扩展,因此在需要时允许变量声明。

#1


6  

The web page is inaccurately characterizing C89.

web页面对C89的描述不准确。

In C89, you could declare variables at the top of any block (not just at the start of a function), but not at any point during a block.

在C89中,您可以在任何块的顶部声明变量(不只是在函数的开头),但不能在块的任何位置声明变量。

In C99 and beyond, you are not constrained to declare variables at the beginning of a block. Specifically, C99 allows you to write:

在C99和beyond中,您不必在块的开头声明变量。具体来说,C99允许你写:

for (int i = 0; i < max; i++)

If you use GCC but need to retain compatibility with MSVC, then you can use -Wdeclaration-after-statement to detect when you declare a variable after a statement (which C89 does not allow).

如果您使用GCC但需要保持与MSVC的兼容性,那么您可以使用- wdeclaration - afterstatement来检测在语句之后(C89不允许)声明变量的时间。

Objective C presumably uses C99 rather than C89 as the standard it extends, so it allows variable declarations when needed.

Objective C使用C99而不是C89作为标准扩展,因此在需要时允许变量声明。