I am encountering problems in understanding the static identifier in the specific case of this program. The context of this program is a lecture about "pointers".
This program's job is to create a new name for a temporary file, it accomplish this (with the help of static int sequence
) by creating a new name every time the function tmp_name
is called.
- first call –> "tmp0"
- second call –> "tmp1"
- ...
[code]
#include <stdio.h>
#include <string.h>
/*******************************************************
* tmp_name -- Return a temporary filename *
* *
* Each time this function is called, a new name will *
* be returned. *
* *
* Returns *
* Pointer to the new filename *
*******************************************************/
char *tmp_name(void){
static char name[30]; /* The name we are generating */
static int sequence = 0; /* Sequence number for last digit */
++sequence; /* Move to the next filename */
strcpy(name, "tmp");
name[3] = sequence + '0';
/* End the string */
name[4] = '\0';
return(name);
}
int main(){
char *tmp_name(void); /* Get the name of temporary file, very first call */
char *name1; /* Name of a temporary file, second call */
char *name2; /* Name of another temporary file, third call */
name1 = tmp_name();
name2 = tmp_name();
printf("Name1: %s\nName2: %s\n", name1, name2);
return(0);
}
So the output of the program (since the printf
function is called) is to print "tmp1" and "tmp2" ("tmp0" cannot be printed, and it is perfectly ok).
So the program is PERFECTLY WORKING, what is the problem then? The problem is that if i remove static
from static char name[30]
the program breaks. It prints this out:
Name1: \340\364\277\357\376
Name2: \340\364\277\357\376
I studied what static does mean and what it implies, for this reason the use of static int sequence
is perfectly clear for me, but i really cannot understand why also the array [name] is declared statically.