LearnFrenzy
Sign in Take a free test

C Const · Find the Error · Question 2

Error: writing through a pointer to const Answer, explanation & discussion

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

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

main.c
#include <stdio.h>

void reset(const int *counter) {
    *counter = 0;
}

int main(void) {
    int clicks = 12;
    reset(&clicks);
    printf("%d\n", clicks);
    return 0;
}
  • A clicks must be const
  • B counter points to const int, so *counter = 0 is not allowed; the parameter should be int * Correct
  • C &clicks is invalid
  • D There is no bug
Correct Answer: Option B

The const in the parameter is a promise not to modify the data, and the function breaks that promise. A function that must write needs a non-const pointer parameter.

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