| ← Previous | 🏠 Homepage | Next Chapter → |
Things switch can’t do:
-
You can't use decimal numbers (float):
switch(3.14) // ❌ Not allowed
switch only works with whole numbers or characters.
-
You can't use math with variables in case:
case a + 3: // ❌ Not allowed
case values must be fixed numbers, not something that changes.
-
You can't repeat the same value in two cases:
case 3:
case 1 + 2: // ❌ This is like writing case 3 again!
You can't use decimal numbers (float):
switch(3.14) // ❌ Not allowed
switch only works with whole numbers or characters.
You can't use math with variables in case:
case a + 3: // ❌ Not allowed
case values must be fixed numbers, not something that changes.
You can't repeat the same value in two cases:
case 3: So why use switch?
Because it’s faster when you have many options to choose from.
But if you need:
-
decimal numbers
-
value ranges (like
x < 5) -
or changing values in
case
Then go with if-else, it’s more flexible.
The Dangerous GOTO
Why avoid goto?
-
Makes code hard to read
-
Confuses the flow of logic
-
Harder to debug
-
Like putting trapdoors in your code
Example:
int goals;
scanf("%d", &goals);
if (goals <= 5)
goto sorry;
else {
printf("Time to switch careers!\n");
exit(0);
}
sorry:
printf("To err is human!\n");
What’s happening?
- If
goals <= 5, it jumps tosorrylabel. -
Otherwise, it exits the program.
-
gotois used to jump directly to a part of code.
But wait — there’s always a cleaner way.
When is goto okay-ish?
goto out; jumps out of all loops like hitting an emergency button!
goto is like a fire exit — use it only when there’s no better way.
Try break or a flag first. They're cleaner and safer!
No comments:
Post a Comment