Handmade Hero » Forums » Code » For noobs from a noob: about static in c
rizoma
39 posts
#7181 For noobs from a noob: about static in c
1 year ago Edited by on June 8, 2016, 3:31 p.m.

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!
mmozeiko
Mārtiņš Možeiko
1349 posts
1 project
#7183 For noobs from a noob: about static in c
1 year ago

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.
rizoma
39 posts
#7211 For noobs from a noob: about static in c
1 year ago Edited by on June 10, 2016, 8:13 a.m.

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ņš
:-)