[Courses] [C] Beginner's Lesson 4B: Errata

Laurel Fan laurel at sdf.lonestar.org
Fri Oct 11 14:07:43 EST 2002


On Fri, Oct 11, 2002 at 04:07:35PM -0400, KWMelvin wrote:
> You know what, now that you point it out, I'm not really sure it works.
> According to what is in the text, only the first element memory[0]
> would be initialed to zero, and the others would not be initialized
> at all.  But for the life of me, I could swear that I've seen that
> somewhere before, but I cannot put my hand on it now. 8^D

Maybe because it's sometimes right, and sometimes wrong. (Isn't C
great?).

K&R says "If there are fewer initializers for an array than the
specified size, the others will be zero for external or static
variables, but garbage for automatics."

external, static, and automatics are somewhat intermediate concepts:

Automatic variables are those that come and go automatically when you
call a function.  All local variables (local variables are those that
belong to a particular function or scope) are automatic, except those
that are static.

External and static variables exist for the entire life of the
program.  External variables are also known as global, or accessible
by any function in a program.  Static variables are local variables
that have been specified (with the 'static' keyword) to exist for the
entire life of the program; multiple calls to the same function use
the same local static variable.

Here's an illustration in code:

#include <stdio.h>

int global_variable = 0;

void increment()
{	
    static int static_variable = 0;
    int automatic_variable = 0;

    global_variable++;
    static_variable++;
    automatic_variable++;

    printf("global is %d, static is %d, and automatic is %d\n",
           global_variable, static_variable, automatic_variable);
}

int main()
{
    increment();
    increment();
    increment();
    return(0);
}

-- 
laurel at sdf.lonestar.org
http://dreadnought.gorgorg.org



More information about the Courses mailing list