iwarv
iwarv

Reputation: 451

ANSI C - scope of variables

C++ programmer here, recently been roped in to do some C programming. Looking for a refresher on the rules of variable scope in ANSI C compliant code.

Is the following code ANSI C compliant?

void foo_func(void)
{
    int i = 0;

    printf("i = %d\n", i);

    for (int j = 0; j < 10; ++j) {
       printf("j = %d\n", j);
    }
}

Does variable j need to be declared at the start of the function? My understanding is that for() implicitly starts a new scope. That is; even before the opening brace.

Does the same apply for while() and if()? And what about do.. while() ?

Do the rules of scope differ between C89 and C99 or later?

Upvotes: 3

Views: 1367

Answers (2)

H.S.
H.S.

Reputation: 12669

>> My understanding is that for() implicitly starts a new scope. That is; even before the opening brace.

Correct. From C11 standards#6.8.5p5 Iteration statements

An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.

This holds true for C99 as well.

>> Does the same apply for while() and if()? And what about do.. while() ?

In if(), while() and do..while() loops you can not declare the variable like if (int j = 0) or while(int j = 0).

Upvotes: 2

P.P
P.P

Reputation: 121387

Does variable j need to be declared at the start of the function?

Yes, if you are using C89. Or, at least you'd need to introduce a scope with { ..} and declare it.

Does the same apply for while() and if()? And what about do.. while() ?

The syntax doesn't permit declaring variables in (i.e., while (int i = 0) isn't valid) them. But you can declare insde them which is allowed in all C standards.

Do the rules of scope differ between C98 and C99 or later?

There's no C98 but yes the rules changed in C99 and later and allows you declare variables in the for loop (as you have in your code).

Is the following code ANSI C compliant?

That depends on what "ANSI C" refers to. It's valid in C99 and later.

Upvotes: 6

Related Questions