Declare local C89 variables at start of scope?

I tried 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 the ANSI C project). You will receive an error message:

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

It works:

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

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

I found many forums where people give this advice, but I have not seen it written in any "official" source, such as the GNU C manual.

+2
source share
3 answers

ANSI C89 requires variables to be declared at the beginning of a scope. It relaxes on the C99.

This is clear when using gcc , when you use the -pedantic flag, which more strictly abides by the standard rules (since it is used by default for C89 mode).

Please note that this is really C89 code:

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

But the use of braces to indicate the scope (and, therefore, the lifetime of variables in this area) does not seem particularly popular, therefore C99 ... etc.

+3
source

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

However, many C89 compilers allow variable declarations to be placed almost anywhere in a block, unless the compiler is in strict mode. This includes GCC, which can be entered into strict mode with -pedantic . Clang uses the target C99 by default, so -pedantic will not affect whether variable declarations can be mixed with code.

MSVC has pretty poor support for C, I'm afraid. It only supports C89 (old!) With several extensions.

+3
source

Now I read in many places that you need to declare variables at the beginning of a code block in which variables exist. 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 operator

{statement-list_opt statement-list_opt}

The declaration must be before operations in the block.

C99 softened this by allowing mixed declarations and statements in the block. In the C99 standard:

(C99, 6.8.2 Compound statement)

Syntax

compound operator:

{block-item-list_opt}

block element list:

block element

item list block

block element:

declaration

Statement

+2
source

Source: https://habr.com/ru/post/977030/


All Articles