Friday, January 16, 2009

A typical C confusion..

Most of the books on C says that a " if we want to make variable global in a file and dnt want that other files can access that variable" what we simple do is to define that variable as static. After that it can't accessed outside the file.

Prove this theory.

for example :

mylib.h
/* Start of file */

void display();

/* End of file */

file1.c

#incude
#include"mylib.h"

static int privateVariable=10;


void display()
{
printf("\n%d \n", privateVariable );

}

/* End of File */

file2.c
/* Start of file */
#include"mylib.h"

int main()
{

display();
privatevariable=15 ; /* Should give a error at this stage */

}

/* End of file */


Just prove the above theory .. i mean just try to execute the above code.
According the Ansi standard this generates a error and it does.
For making things simpler i hve already written down the whole code.
All you need to do is execute it. According to aftr the above code ,its a very easy job to do.

If you want to read more about this issue just read ' The C programming Language ' by Dennis Ritchi (dnt remember the chapter ) .