← The C Language Lesson 29 of 77 · 10 XP

Scope

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A local variable is declared inside a { } block and is visible only in it. It is created on entering the block and disappears on leaving it:

int main(void)
{
    int x = 1;
    {
        int x = 2;        // a different x that "shadows" the outer one
        printf("%d\n", x);   // 2
    }
    printf("%d\n", x);       // 1
}

A global variable is declared outside functions and is visible to all the functions in the file. Unlike local variables, global ones are automatically set to zero.

int counter = 0;          // global

void tick(void) { counter++; }

Global variables are convenient but dangerous: anyone can change them, and the program becomes hard to understand. Pass data through parameters.

Never return the address of a local variable from a function: once the function exits, that memory is no longer yours.

int *bad(void)
{
    int x = 5;
    return &x;            // a dangling pointer! The compiler will warn you
}

Task. Finish the function next_id(), which returns the next number on every call: 1, 2, 3… Use a global variable. The program reads n and prints n numbers.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.