아래 예처럼 전역 변수를 선언하지 않고도 가능할까요?
네, 다른 답변에서 보여 준 것처럼 당연히 가능합니다.
다만 전역 변수를 무조건 unappealing하다고 치부하지는 마세요. 나름 쓸 곳이 있습니다.
C에는 모듈 안에서는 접근할 수 있지만 밖으로 노출되지는 않는 모듈 범위도 있다는 걸 기억하세요. 그런 변수도 고려할 만합니다.
따라서 이런 코드는 충분히 합리적입니다:
#include <stdio.h>
static char entry[12]; // Module scope is fine
static char *read_entry() {
scanf("%s",entry);
return entry;
}
int main(void) {
printf("%s",read_entry());
}
영어에서 번역·원문 보기
Can this work without declaring an global variable like the one below?
Yes, certainly, as demonstrated by the other response.
Still, don't dismiss every global variable as unappealing, because they do have uses.
Remember also that C supports module scope, where something can be accessed inside its module but isn't exposed outside it. Those variables deserve consideration too.
This, therefore, is entirely reasonable:
#include <stdio.h>
static char entry[12]; // Module scope is fine
static char *read_entry() {
scanf("%s",entry);
return entry;
}
int main(void) {
printf("%s",read_entry());
}