KU COSE101 2018기말고사 1번 문제

less than 1 minute read

             
2016 기출 1번 2번 3번 4번 5번  
2017 기출 1번 2번 3번 4번 5번  
2018 기출 1번 2번 3번 4번 5번 6번

다음 프로그램의 출력을 작성하시오.

#include <stdio.h>

static void func(int n)
{
  int x = n+1;
  printf("x = %d\n",x);
  if(x%2){
    static int n = 10;
    printf("n = %d\n", n);
    n++;
  }
  else{
    static int n = 20;
    printf("n = %d\n", n);
    n++;
  }
}

int main()
{
  func(10);
  func(11);
  func(12);
  func(13);
}

정답
x = 11
n = 10
x = 12
n = 20
x = 13
n = 11
x = 14
n = 21

static variables는 함수를 다시 호출하더라도 이전에 사용했던 변수가 저장되기 때문에 변하지 않는다.

또한, if-else문을 보면 각 블록별로 static 변수가 존재하는데, 

각각의 static은 각 블록 안에서만 작용하여 n이 따로 저장된다.

Comments