본문 바로가기
<프로그래밍 언어>/[C 언어]

[C 언어] Syntactic Sugar 문법적 설탕

by 자라나는 콩 2022. 2. 28.

문법적 설탕? 설탕은 맛있고 접근성도 좋고 쉽다! 문법적 설탕도 동일한 문법적 기능도 더 직관적이고 읽기 쉽게 만드는 것이다.

다음 예시를 보자.

 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int scores[3];

    scores[0] = get_int("Score: ");
    scores[1] = get_int("Score: ");
    scores[2] = get_int("Score: ");

    printf("Average: %f\n", (scores[0] + scores[1] + scores[2]) / 3.0);

 

3개의 스코어의 평균을 내는 코딩이다. 문법적 문제는 없지만 똑같은 걸 3번 반복해야 한다는 번거로움이 있다. 하지만 문법적 설탕을 사용한다면?

 

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int scores[3];

    for (int i = 0; i < 3; i++)
    {
      scores[i] = get_int("Score: ");
    }

    printf("Average: %f\n", (scores[0] + scores[1] + scores[2]) / 3.0);
}

 

scores[?] = get_int("Score: "); 을 3번 쓸 것을  

for (int i = 0; i < 3; i++)
    {
      scores[i] = get_int("Score: ");
    }

로 간단하게 줄였다!

댓글