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