For noobs from a noob: about static in c

While reading the k&r book I found an interesting example (at least for a noob like me) of what I think is a static locally scoped variable used in a good way:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
char *month_name(int n)
{
    static char *name[]=
    {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };

    return (n < 1 || n > 12) ? name[0] : name[n];
}


So as you can see the function return a string, based on the input n. So for my little knowledge this make sense since a static variable is initialized just the first time, and it is scoped just in the current block. If nobody need to access this variable the thing make perfectly sense. And that make me think about an earlier QA episode of Hmh, when somebody asked about static const, that example can explain why static const can be used.

I hope somebody like me find that useful!
And please correct me if I'm wrong :)
see ya!

Edited by rizoma on
In this case it will be even better - compiler will notice that values you are initializing array are known at compile time. So it will move whole array to data segment and there will be no need to initialize anything in code the first time function is called.

Here's the output from gcc:
1
2
3
4
5
6
7
8
9
month_name:
	leal	-1(%rdi), %edx
	movl	$.LC0, %eax
	cmpl	$11, %edx
	ja	.L1
	movslq	%edi, %rdi
	movq	name.1758(,%rdi,8), %rax
.L1:
	ret

As you can see it references array with global symbol "name.1758" - no initialization is done in code.
mmozeiko
As you can see it references array with global symbol "name.1758" - no initialization is done in code.

Ahh the magic of assembly, I will try to look at the disassembly more often!
Thanks Mr.Mārtiņš
:-)

Edited by rizoma on