申报范围的开头C89局部变量? [英] Declare C89 local variables in the beginning of the scope?

查看:156
本文介绍了申报范围的开头C89局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到这一点的ANSI C:

I was trying to do this in ANSI C:

include <stdio.h>
int main()
{
    printf("%d", 22);
    int j = 0;
    return 0;
}

这不会在Microsoft 的Visual C ++ 2010 工作(在ANSI C项目)。你得到一个错误:

This does not work in Microsoft Visual C++ 2010 (in an ANSI C project). You get an error:

error C2143: syntax error : missing ';' before 'type'

这不工作:

include <stdio.h>
int main()
{
    int j = 0;
    printf("%d", 22);
    return 0;
}

现在我在你已经在code座中的变量存在的开头声明变量很多地方阅读。这是一般的ANSI C89?

Now I read at many places that you have to declare variables in the beginning of the code block the variables exist in. Is this generally true for ANSI C89?

我发现很多论坛上,人们给这个意见,但我没有看到它写在喜欢的 GNU C 手册。

I found a lot of forums where people give this advice, but I did not see it written in any 'official' source like the GNU C manual.

推荐答案

ANSI C89要求变量在范围的开始申报。这被放宽C99。

ANSI C89 requires variables to be declared at the beginning of a scope. This gets relaxed in C99.

这是 GCC明确当您使用 -pedantic 标志,它更紧密地强制执行的标准规则(因为它默认为C89模式)。

This is clear with gcc when you use the -pedantic flag, which enforces the standard rules more closely (since it defaults to C89 mode).

请注意,虽然,这是有效的C89 code:

Note though, that this is valid C89 code:

include <stdio.h>
int main()
{
    int i = 22;
    printf("%d\n", i);
    {
        int j = 42;
        printf("%d\n", j);
    }
    return 0;
}

但使用括号来表示一个范围(因而在该范围变量的寿命)​​的似乎并不特别受欢迎,因此C99 ...等。

But use of braces to denote a scope (and thus the lifetime of the variables in that scope) doesn't seem to be particularly popular, thus C99 ... etc.

这篇关于申报范围的开头C89局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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