LearnFrenzy
Sign in Take a free test

C Const · Find the Error · Question 7

A const string passed to a function that modifies it Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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

main.c
#include <ctype.h>
#include <stdio.h>

void capitalise(char *s) {
    s[0] = (char) toupper((unsigned char) s[0]);
}

int main(void) {
    const char *msg = "hello";
    capitalise(msg);
    puts(msg);
    return 0;
}
  • A toupper() needs an int
  • B msg points to a read-only string literal; passing it to a char * parameter discards const, and the write crashes Correct
  • C puts() cannot print const strings
  • D There is no bug; it prints Hello
Correct Answer: Option B

The compiler warns that passing const char * to char * discards a qualifier – exactly the bug. Pass a writable copy instead: char msg[] = "hello";.

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