Course contentsShow
← C
Lesson 262 of 1,2194. Control FlowFree lesson

Switch restrictions: integral types only

Switch restrictions: integral types only

What you'll learn: Why the C switch statement only works with whole numbers and characters, and why you cannot use it for decimal numbers or text strings.

The "Whole Number" Club

Imagine a switch statement as a mechanical sorting machine at a post office. For the machine to work efficiently, it needs to drop items into specific, numbered bins. Because the machine is built for speed, it requires a simple, exact match—like "Bin 5" or "Bin 10."

In C, the switch statement is optimized for this kind of speed. To achieve this, it only accepts integral types. These are data types that represent whole values without any fractional parts.

You can use a switch with:

  • int (standard integers like 1, 42, or -10)
  • char (letters like 'a' or 'Z', because C treats them as their underlying numeric ASCII codes)
  • enum (named constants that represent integers)

Why Floats and Strings Are Left Out

You might be tempted to switch on a float (like 3.14) or a string (like "Apple"). However, C does not allow this.

Floating-point numbers are notoriously "fuzzy" in computer memory; 3.14 might actually be stored as 3.1399999, making an exact match unreliable for a fast sorting machine. As for strings, they are sequences of multiple characters, and C cannot compare an entire word against a case label in a single, simple step. If you need to compare decimals or words, you must use an if-else chain instead.

A Valid Example

Here is how you use a character (an integral type) to drive a switch:

#include <stdio.h>

int main() {
    char grade = 'B';

    // This works because 'B' is internally treated as the integer 66
    switch (grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Well done!\n");
            break;
        default:
            printf("Keep trying!\n");
    }

    return 0;
}

If you tried to replace grade with a float or a word in double quotes, the C compiler would stop you with an error. By sticking to integers and characters, you ensure your switch is fast and predictable.

Key takeaway

A switch statement only accepts integral types (int, char, enum); it cannot be used with floating-point numbers or strings.