Scoping question in C

bob fcsoft-3Emkkp+1Olsmp8TqCH86vg at public.gmane.org
Fri Jun 10 13:18:19 UTC 2005


In C scope is (in its most useful part anyway) connected to the source file 
in which you are defining your global variable.

For example if in source file  bob.c you put

int a;

int func1()
{
}

int func2()
{
}

Then "a" will be accessable as a global variable by both func1 and func2.    
This variable "a" will be allocated on the heap and will persist for the 
entire duration of your program.   ie. the value will "stick" after func1() 
exits.

If your application has another C source file called gloria.c as:

int main()
{
exit(0);
}

then "a" will not be available inside main unless you explicitly use the 
extern modifier as in:

extern int a;

in the area above main().    Note:  normally you'd reverse this allocation 
scheme and have the explicit delaration in gloria.c (which contains main) and 
the extern declaration in bob.c (which contains some utility functions).

If you wish to restrict the scope of "a" to only the file bob.c you simply 
declare it as:

static int a;

and the other files can't use "extern" to manipulate it. 

Hope this helps.


bob
PS.
If anyone wants more info about this kind of thing,   feel free to consult 
the lesson#3 of the latest iCanProgram course at:

	http://www.icanprogram.com/33ux/main.html



On June 9, 2005 06:48 pm, you wrote:
> I have question regarding scope of static string inside C function.
> Suppose I have
>
>     char *x;
>
>     int func ()
>     {
> 	x = "something";
> 	return (1);
>     }
>
> where 'x' is global variable being used elsewhere.  Can I use 'x' after
> func() exits?  That is, is 'x' still pointing to string "something"?
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list