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