정보처리기사

[정보처리기사] C언어 특강 49~52강 정리(static 변수)

jaeheon0520 2024. 10. 9. 14:06

static 변수

단 한번만 초기화 하고, 그 이후에는 전역변수처럼 프로그램이 종료될때까지 메모리공간에 존재하는 변수

 

초기값이 지정이 안되면 자동으로 0이 대입

 

 

#incldue <stdio.h>

void funCount();
int main() {
    int num;
    for(num=0; num<2; num++)
    	funCount();
    return 0;
}

void funCount() {
	int num = 0;
    static int count;
    printf("num=%d, count=%d\n", ++n, count++); 
}

// num=1, count=0
// num=1, count=1

// printf()에서 후치증감이 있으면 출력한 다음에 증감해주기
// printf()에서 전위증감이 있으면 증감을 수행한 다음 출력해주기

 

#include <stdio.h>

int fo(void) {
    int var1 = 1;
    static int var2 = 1;
    return (var1++) + (var2++);
}

void main() {
    int i = 0, sum = 0;
    while (i < 3) {
        sum = sum + fo(); // 2 3 4
        i++
    }
    printf("sum=%d\n", sum); // 9
}

 

#include <stdio.h>

int funcA(int n) {
    static int s = 1;
    s *= n
    return s;
}

int funcB(int n) {
    int s = 1;
    s *= n;
    return s;
}

void main() {
    int s1, s2;
    s1 = funcA(2);
    printf("F1=%d,", s1); // 2
    s1 = funcA(3);
    printf("F2=%d,", s1); // 6
    s2 = funcB(2);
    printf("F3=%d,", s2); // 2
    s2 = funcB(3);
    printf("F4=%d,", s2); // 3
}

 

#include <stdio.h>
int a = 10;
int b = 20;
int c = 30;

void func() {
    static int a = 100;
    int b = 200;
    a++; // 101 102
    b++; // 201 201
    c = a; // 101 102
}

void main() {
    func();
    func();
    printf("a=%d, b=%d, c=%d\n", a, b, c); // 10 20 102
}