LearnFrenzy
Sign in Take a free test

Control Instructions · Find the Error · Question 1

Error: using switch on a string in C Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    const char *cmd = "start";
    switch (cmd) {
    case "start": puts("starting"); break;
    case "stop":  puts("stopping"); break;
    }
    return 0;
}
  • A The cases need default
  • B switch needs an integer expression and integer constant labels; strings must be compared with strcmp() Correct
  • C cmd must be a char array
  • D There is no bug
Correct Answer: Option B

C cannot switch on strings. Use if (strcmp(cmd, "start") == 0) … else if …, or convert the string to an enum value first and switch on that.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links