Use static in function - C

Hello,

Why we should use "static" char of array in function?

Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>

char* binbin(unsigned n);

int main()
{
	unsigned b = 21;

	for (int i = 0; i < 16; i++)
	{
		printf_s("%s\t0x%04X\t%4d\n", binbin(b), b, b);
		b <<= 1;
	}

	return(0);
}

char* binbin(unsigned n)
{
	static char bin[17]; // Why bin should be static?

	for (int i = 0; i < 16; i++)
	{
		bin[i] = n & 0x8000 ? '1' : '0';
		n <<= 1;
	}
	bin[16] = '\0';

	return(bin);
}
Because if it's not static, the array only exists for the lifetime of the function itself. Pointing to and dereferencing the local array from outside the function itself would be undefined behavior.
Last edited on
Note that you don't need () around the returned value. Return is a statement, not a function.

 
return bin;
Topic archived. No new replies allowed.