Declare C89 local variables in the beginning of th

2019-01-27 01:29发布

问题:

I was trying to do this in ANSI C:

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

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'

This does work:

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

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?

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.

回答1:

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

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

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;
}

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.



回答2:

This is absolutely true for C89. (You're better off looking at documentation for the language, e.g., books and standards. Compiler documentation usually only documents differences between the language the compiler supports and ANSI C.)

However, many "C89" compilers allow you to put variable declarations nearly anywhere in a block, unless the compiler is put in a strict mode. This includes GCC, which can be put into a strict mode with -pedantic. Clang defaults to a C99 target, so -pedantic won't affect whether you can mix variable declarations with code.

MSVC has rather poor support for C, I'm afraid. It only supports C89 (old!) with a few extensions.



回答3:

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 C 89?

Yes, this is required in the syntax of a compound statement in the C89/C90 Standard:

(C90, 6.6.2 Compound statement, or block)

Syntax

compound-statement

{ declaration-list_opt statement-list_opt }

Declaration have to be before statements in a block.

C99 relaxed this by allowing mixing of declarations and statements in a block. In the C99 Standard:

(C99, 6.8.2 Compound statement)

Syntax

compound-statement:

{ block-item-list_opt }

block-item-list:

block-item

block-item-list block-item

block-item:

declaration

statement