Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

c - Declare C89 local variables in the beginning of the scope?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", i);
    {
        int j = 42;
        printf("%d
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...