Syntatic Sugar

  • ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด ์ฐจ์›์—์„œ ์ œ๊ณต๋˜๋Š” ๋…ผ๋ฆฌ์ ์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ‘œํ˜„ํ•˜๋Š” ๊ฒƒ
  • ์ค‘๋ณต๋˜๋Š” ๋กœ์ง์„ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ๋‚˜ํƒ€๋‚˜๊ฒŒ ๋˜์—ˆ๋‹ค.

์›๋ฌธ

Syntactic sugar, or syntax sugar, is a visually or logically-appealing โ€œshortcutโ€ provided by the language, which reduces the amount of code that must be written in some common situation.

์ดํ•ด๋ฅผ ๋•๊ธฐ ์œ„ํ•œ Example

Suger๊ฐ€ ๋ถ€์กฑํ•œ ํ‘œํ˜„

int a;
if(SomeFunction() == 2)
   a = 4;
else
   a = 9;

๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ๋…ธ๋ ฅํ•˜๋Š” ์—”์ง€๋‹ˆ์–ด์˜ ๋ฐฉ๋ฒ•

  • ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ณ  ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹
public T Iif<T>(bool condition, T ifTrue, T ifFalse)
{
   if(condition) return ifTrue;
   return ifFalse;
}
...
//usage
int a = Iif(SomeFunction() == 2, 4, 9);

ํ•˜์ง€๋งŒ ์–ธ์–ด์ฐจ์›์—์„œ ์ œ๊ณต๋˜๋Š” Syntatic Sugar

  • ์‚ผํ•ญ ์—ฐ์‚ฐ์ž
int a = SomeFunction() == 2 ? 4 : 9;

๋ช‡๊ฐ€์ง€ Syntatic Sugar Example

Compound Assignment Operators

Not Syntatic Sugar

x = x + 5;

Syntatic Sugar

x += 5;
x++;
++x;
--x;

Ternary Operator

Not Syntatic Sugar

bool passed;
if (mark >= 50) {
    passed = true;
} else {
    passed = false;
}

Syntatic Sugar

bool passed = mark >= 50 ? true : false;

Switch statement

Not Syntatic Sugar

if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
	puts("Letter IS a vowel");
} else {
	puts("Letter is NOT a vowel");
}

Syntatic Sugar

switch (letter) {
case 'a': case 'e': case 'i': case 'o': case 'u':
	puts("Letter IS a vowel");
	break;
default:
	puts("Letter is NOT a vowel");
}

for loops (C-style)

Not Syntatic Sugar

i = 0;
while (i < num_rows) {
	j = 0;
	while (j < num_cols) {
		matrix[i][j] = 1;
		j++;
	}
	i++;
}

Syntatic Sugar

for (i = 0; i < num_rows; i++) {
	for (j = 0; j < num_cols; j++) {
		matrix[i][j] = 1;
	}
}

Reference