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;
}
}