23.6.25

20250623 17:00 Chapter 4 : Switching Decisions in C

                              

← Previous 🏠 Homepage Next Chapter →
                                           


Things switch can’t do:

  1. You can't use decimal numbers (float):

    switch(3.14) // ❌ Not allowed
    

    switch only works with whole numbers or characters.

  2. You can't use math with variables in case:

    case a + 3: // ❌ Not allowed
    

    case values must be fixed numbers, not something that changes.

  3. You can't repeat the same value in two cases:

    case 3: 
         case 1 + 2: // ❌ This is like writing case 3 again!



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


"GOTO" is like teleportation — fast, but very confusing.

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 to sorry label.
  • Otherwise, it exits the program.

  • goto is used to jump directly to a part of code.

But wait — there’s always a cleaner way.

When is goto okay-ish?


for (i = 1; i <= 3; i++)
for (j = 1; j <= 3; j++) for (k = 1; k <= 3; k++) if (i == 3 && j == 3 && k == 3) goto out; else printf("%d %d %d\n", i, j, k); out: printf("Escaped the loop!\n");

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

rating System

Loading...

A Friendship Story of Learning Data Structures with C

Sr. No. DSU BLOGS CHAPTERS 1 Array Operations in C, The Group of Friendship (Create, Insert, Delete ...