[Courses] variables in c...

kevin lyda kevin at ie.suberic.net
Mon Jun 24 00:28:06 EST 2002

somehow i came across your c course info.  not sure how since the last
thing i conciously remember searching for was about a festival error
i had.

anyway, c variables.  i dunno if this will be useful, but i just had a
long discussion about this in the irish lug irc channel.  i've always used
this question in interviews (after it stumped me in an interview, evil):

    what is special about "static int x;" outside of a function.

the answer i've always looked for is "it's scope is limited to the file,"
which i feel is true in a cs kind of way.  but in c terms i've come
to realise over the past few days that it means that x has "internal

anyway, my general approach is that there are four types of variable
scope in c:

    program scope:
	--->file foo.c:
	int x;

	--->file bar.c:
	extern int x;

    file scope:
	--->file foo.c
	static int x;

    function scope:
	--->file foo.c
	int func(void) { int x; ... }

    block scope:
	--->file foo.c
	int func(void) { if (expr) { int x; ... } else { ... } }

in addition to scope there's a concept of lifetime for variables.  a block
or function scoped variable that is declared static will exist for the
lifetime of the program.  if declared with an assignment (static int x =
5;) the assignment happens only once; w/o an assignment it's set to 0.
from then on it maintains it's value even though it goes in and out
of scope.

at work we've been discussing memory allocation.  this site had a good
list of resources:


in addition it's a really good idea to compile your programs with
-Wall set.  the easy way to do this in a Makefile is to add it to CFLAGS
like soo:

    --->file Makefile
    CFLAGS+= -Wall

    foo: foo.o bar.o floyd.o
	    $(CC) -o $@ $^


kevin at suberic.net     that a believer is happier than a skeptic is no more to
fork()'ed on 37058400   the point than the fact that a drunken man is happier
meatspace place: inle      than a sober one. the happiness of credulity is a
http://suberic.net/~kevin    cheap & dangerous quality -- g.b. shaw

More information about the Courses mailing list